For other types an index expression
a[b]is equivalent to*std::ops::Index::index(&a, b), or*std::ops::IndexMut::index_mut(&mut a, b)in a mutable place expression context.
Okay, so Rust auto-dereferences index operations. Cool. This fails expectedly:
fn main() {
let s = String::from("abc123");
let a = s[3..]; // "str is unsized" error
}
Throws:
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/main.rs:6:9
|
6 | let a = s[3..];
| ^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `str`
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
help: consider borrowing here
|
6 | let a = &s[3..];
| ^
No surprises there! Okay, let's fix it and also make this example a little bit more interesting:
fn main() {
let s = String::from("abc123");
let a = &s[3..]; // fixed
let b = a.parse::<i32>();
assert_eq!(Ok(123), b); // passes
}
But it gets weird if I try to combine statements a and b into a single statement c:
fn main() {
let s = String::from("abc123");
let a = &s[3..]; // fixed
let b = a.parse::<i32>();
assert_eq!(Ok(123), b); // passes
let c = &s[3..].parse::<i32>();
assert_eq!(Ok(123), c); // fails!?
}
Throws:
error[E0308]: mismatched types
--> src/main.rs:11:5
|
11 | assert_eq!(Ok(123), c);
| ^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Result`, found reference
|
= note: expected enum `Result<{integer}, _>`
found reference `&Result<i32, ParseIntError>`
"Expected Result, found reference"? What reference? Where? After some trial and error I managed to fix the issue problem by dropping the leading & from statement c to create the correct statement d below:
fn main() {
let s = String::from("abc123");
let a = &s[3..]; // fixed
let b = a.parse::<i32>();
assert_eq!(Ok(123), b); // passes
let c = &s[3..].parse::<i32>();
// assert_eq!(Ok(123), c); // fails!?
let d = s[3..].parse::<i32>(); // why no more "str is unsized" error!?
assert_eq!(Ok(123), d); // passes again
}
The above code compiles and passes all assertions but why is there no "str is unsized" error in statement d like there was in our very first example of statement a back at the top of this post!?
Can someone please help make this make sense? Thank you.