Hello!
How to handle the operator ? in the for_each
function?
Code:
fn main()
{
let v = vec![vec!["1", "2", "3"], vec!["4", "5", "6"], vec!["7", "8", "9"]];
let do_something = |name: &String| -> Result<u8, String>
{
let n : u8 = name.parse().map_err(|_|{ format!("cannot convert!") })?;
if n == 42 { return Err("Error!!!!!".to_string()); }
return Ok(n);
};
let print = |v: Vec<Vec<&str>>| -> Result<(), String>
{
v.iter().for_each(|v1|{
println!("vec:");
v1.iter().for_each(|v2|{
println!("\t {:?}", v2);
do_something(&v2.to_string())?;
});
});
return Ok(());
};
let _error_msg = print(v);
}
Error:
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:21:17
|
19 | v1.iter().for_each(|v2|{
| ________________________________-
20 | | println!("\t {:?}", v2);
21 | | do_something(&v2.to_string())?;
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a closure that returns `()`
22 | | });
| |_____________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
Rust Playground: CLICK ME!