I am trying, quite unsuccessfully, to play around with slices.
I have reduced my first issue to:
fn at<'a, T>(slice: &'a [T], index: usize) -> &'a T {
let item = slice[index];
item
}
It is my expectation that the return type of slice[index]
be a reference, given the documentation:
pub trait Index<Index> {
type Output;
fn index(&'a self, index: &Index) -> &'a <Self as Index<Index>>::Output;
// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
However, the compiler gives me an error:
error[E0308]: mismatched types --> src/main.rs:3:5 | 3 | item | ^^^^ expected reference, found type parameter | = note: expected type `&'a T` found type `T`
Which I interpret as meaning that the type of item
does not match the return type of the function (I introduced item
solely for debugging purpose, to split expression evaluation from return).
If I switch the return type to T
, which is the type of item
, I get another error message:
error[E0508]: cannot move out of type `[T]`, a non-copy slice --> src/main.rs:2:16 | 2 | let item = slice[index]; | ^^^^^^^^^^^^ | | | cannot move out of here | help: consider using a reference instead: `&slice[index]`
After tinkering a bit, I found two work-arounds:
fn at<'a, T>(slice: &'a [T], index: usize) -> &'a T {
&slice[index]
// ^
}
fn at<'a, T>(slice: &'a [T], index: usize) -> &'a T {
let ref item = slice[index];
// ^~~
item
}
forcing the type to be a reference does the trick.
Why are these shenanigans necessary in the first place? Am I doing something wrong?