Reputation: 12111
Why does this
fn main() {
let test = "5% of foo".to_string();
let result: i32 = test.split('%').collect()[0].parse().unwrap_or(0);
}
cause an error
error[E0282]: type annotations needed
--> src/main.rs:4:23
|
4 | let result: i32 = test.split('%').collect()[0].parse().unwrap_or(0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type for `B`
This doesn't help either:
let result: i32 = test.to_string().split('%').collect()[0].parse().unwrap_or(0i32);
Upvotes: 11
Views: 8782
Reputation: 16198
fn main() {
let test = "5% of foo".to_string();
let result: i32 = test.split('%').collect::<Vec<_>>()[0].parse().unwrap_or(0);
}
collect()
can become any type that implements FromIterator
so a type hint is required.
Alternatively, you can make it more efficient by utilizing lazy iterators.
fn main() {
let test = "5% of foo".to_string();
let result: i32 = test.split('%').next().unwrap_or("0").parse().unwrap_or(0);
}
Upvotes: 12