Why can we define a reference of array directly?

While leaning Rust, I see the following code.

let arr = &[0; 5];
arr

I wonder

  1. Why can we use & before an array in the example above but not if I change [0; 5] to vec![0; 5]?
  2. What do we use &[0; 5] instead of [0; 5]? What is the advantage of the first way?
  1. It is legal to write let arr = &vec![0; 5], but because the vector is heap-allocated when the code is run, it will be put in a temporary and will only live as long as the function, so you can't return a reference to it. By contrast, [0; 5] is promoted to a constant, it will be put in the static data of the binary, so &[0; 5] can have 'static lifetime and can be returned from the function.

  2. &[T] is often useful for operations that need access to an array without consuming it (i.e. by reference instead of by value, which involves a bit copy of the [0; 5] array).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.