I was trying to iterate over a subsection of a vector of strings, i.e. a subslice of Vec<String>
. Within each iteration, I wanted to pass the string as a slice to a function.
I didn't notice that Vec::get
returns an Option
, and thought I could just directly iterate over the return value:
fn take_str(s: &str) {
println!("{}", s);
}
fn main() {
let str_vec: Vec<String> =
["one", "two", "three", "uno", "dos", "tres"].iter().map(|&s|
s.into()).collect();
for s in str_vec.get(0..3) {
take_str(&s); // Type mismatch: found type `&&[std::string::String]`
}
}
Clearly, I was expecting s
to be a String
, but it's actually &[String]
. This is because my for loop is actually iterating over the Option
returned by Vec::get()
.
I also wrote the following code, which demonstrates that the for
loop is in fact unwrapping an Option
:
let foo = Option::Some ( ["foo".to_string()] );
for f in foo {
take_str(&f); // Same error as above, showing `f` is of type `&[String]`
}
But this is incredibly confusing; I never expected (until I wrote this code and figured out what it's actually doing) that Option
could be unwrapped by iterating over it. Why is that supported? What use case is there for iterating over an Option
?