Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a non-borrowed slice?

Tags:

slice

rust

If I try this:

let vector = vec![1, 2, 3];
let slice = vector[1..2];

I get a compiler error:

error[E0277]: the trait bound `[{integer}]: std::marker::Sized` is not satisfied
 --> src/main.rs:3:9
  |
3 |     let slice = vector[1..2];
  |         ^^^^^   ------------ help: consider borrowing here: `&vector[1..2]`
  |         |
  |         `[{integer}]` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[{integer}]`
  = note: all local variables must have a statically known size

I get that we need let slice = &vector[1..2] as the compiler kindly suggests. This makes sense: a slice always comes from another value, thus you need to borrow the vector in this example.

However, I tried this:

let vector = vec![1, 2, 3];
let borrowed_vector = &vector;
let slice = borrowed_vector[1..2];

and I am back to the same error.

I ask because it seems a bit weird to require the &vector[] syntax if in fact borrowing (&) is always required.

like image 961
fabiim Avatar asked Jan 29 '26 00:01

fabiim


1 Answers

A non-borrowed slice ([T]) exists, but you cannot use it as value as-is. It is only useful in other types where it is behind a pointer of some kind. For example (not exhaustive):

  • In borrowed slices: &[T]
  • In boxed slices (i.e. owned slices): Box<[T]>
  • In ref-counted slices: Rc<[T]>

That is because the compiler cannot know what the size of an unsized type on the stack but a pointer has a known size.

The type can also be used as part of a trait bound for static polymorphism: U: AsRef<[T]>.

It seems a bit weird to require this syntax &vector[] if in fact borrowing (&) is always required.

It is not always required to use an & with the indexing syntax because sometimes the referenced value can be dereferenced:

let scores = vec![1, 2, 3];
let score = scores[0];

See also:

  • What is the return type of the indexing operation?
like image 56
Boiethios Avatar answered Jan 30 '26 16:01

Boiethios