Reference to an array without the owner

This "weird" piece of code:

let x : &[_] = &[0, 1, 2];
match *x {
    _ => ()
}

I found it here Drop semantics and temporary value lifetimes in while let
It's "weird" to me because it's a reference to an array, my understanding is that nobody owns this array so I'm wondering why rust compiles it at all. Is this something like static strings then?

Yes. That array gets compiled into an immutable global variable, just like string constants.

1 Like

It still works if you do give it an owner:

let z = vec![1usize];
let x: &[_] = &z;
match *x {
    _ => (),
}

Playground.

To me these specific semantics are somewhat weird, but it seems that in some cases, the compiler is matching on the length of the array:

struct Foo;
let z = vec![Foo];
let x: &[_] = &z;
match *x {
    [_, _] => println!("Two"),
    [_] => println!("One"),
    _ => println!("Zero"),
}

Which is permitted, but the following code means that _ has very special meaning in terms of how the compiler implements match statements:

struct Foo;
let z = vec![Foo];
let x: &[_] = &z;
match *x {
    [_y, _] => println!("Two"),
    [_] => println!("One"),
    _ => println!("Zero"),
}

Which errors out with

   Compiling playground v0.0.1 (/playground)
error[E0508]: cannot move out of type `[main::Foo]`, a non-copy slice
 --> src/main.rs:5:11
  |
5 |     match *x {
  |           ^^
  |           |
  |           cannot move out of here
  |           help: consider borrowing here: `&*x`
6 |         [_y, _] => println!("Two"),
  |          --
  |          |
  |          data moved here
  |          move occurs because `_y` has type `main::Foo`, which does not implement the `Copy` trait

Which only strengthens how intrinsic match statements are to Rust, and that you can't really re-implement them in user code (Ignoring derivative statements, like if let, while let, or even ?).

What this means for your question, is that if the patterns in your match arms do not consume the values, it's almost like the values were never there.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.