I am having difficulty understanding why the following two code examples are different. First the one that works:
fn main() {
let v: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
let t = &v[2..4];
for x in t {
println!("{}", x);
}
}
Secondly, the one that does not compile:
fn main() {
let v: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
let s = &v;
let t = s[2..4];
for x in t {
println!("{}", x);
}
}
error[E0277]: the size for values of type `[i32]` cannot be known at compilation time
--> src/main.rs:4:9
|
4 | let t = s[2..4];
| ^ doesn't have a size known at compile-time
in the second example, s is already an &Vec<i32>
. is it not the same as the first example, but with &v
divided into two lines instead of one?
the second example is alternatively fixed by adding an additional & to s, like below:
fn main() {
let v: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
let s = &v;
let t = &s[2..4];
for x in t {
println!("{}", x);
}
}
is the issue that in the second example, in the right-hand expression, s is automatically de-referenced before the slice is created and so it evaluates to [i32]
not &[i32]
? can anyone explain why the second example is different than the first? maybe spreading something out over two lines doesn't guarantee it evaluates to the same type, because its a different order of operations?