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.
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):
&[T]Box<[T]>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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With