Rust allows explicit type definition at variable declaration (although it seems that such syntax is rarely used by some reasons). E.g. such declarations are valid:
let number: i32 = 10;
let (tuple_value1, tuple_value2): (i32, String) = (10, String::from("Text"));
let (numeric_value, bytes): (i32, &[u8]) = (10, tuple_value2.as_bytes());
But how variable types can be explicitly defined in the for
loop? I'm currently studying The Rust Programming Language book's chapter 4.3. I'm trying to apply type definition at variables declaration in the for
loop in listing 4-10:
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
Nevertheless when trying to supply mentioned listing's for
loop with the type definition
fn first_word(s: &String) -> usize {
let bytes: &[u8] = s.as_bytes();
for (i, item): (usize, std::iter::Enumerate<std::slice::Iter<u8>>) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
I get:
error: expected `in`, found `:`
--> src/main.rs:7:15
|
7 | for (i, item): (usize, &[u8]) in bytes.iter().enumerate() {
| ^ expected `in` here
error[E0308]: mismatched types
--> src/main.rs:4:36
|
4 | fn first_word(s: &String) -> usize {
| ____________________________________^
5 | | let bytes: &[u8] = s.as_bytes();
6 | |
7 | | for (i, item): (usize, &[u8]) in bytes.iter().enumerate() {
... |
13 | | s.len()
14 | | }
| |_^ expected usize, found ()
|
= note: expected type `usize`
found type `()`
error: aborting due to 2 previous errors
error: Could not compile `hello_world`.
So far the book doesn't contain a description of how to perform an explicit type definition in the loops. So did for me googling. My question is about the proper type definition syntax in the for
loop (if such exists, I'm strongly hope so).