I have a function passed to and_then
that returns a type not known to the compiler. When chained with other option methods, type annotations are required.
fn main() {
let w = Some("hi".to_string());
let x: Option<&String> = w.as_ref();
//fails:
let y: Option<String> =
x.and_then::<String, FnOnce(Option<&String>) -> Option<String>>(|_inner: &String| None);
//ok:
let y: Option<String> = x.and_then(|_inner: &String| None);
}
Adding the mandatory annotations causes this compiler error:
error: the `and_then` method cannot be invoked on a trait object
--> src/main.rs:7:11
|
7 | x.and_then::<String, FnOnce(Option<&String>) -> Option<String>>(|_inner: &String| None);
| ^^^^^^^^
I assume it is complaining about the FnOnce
trait, but I don't see what this has to do with x
.
I would like to understand what is going wrong here.
Ultimately, the goal is to have this and_then
in a chained statement, which is why the annotations are needed.
let y = x
.and_then::<String, FnOnce(Option<&String>) -> Option<String>>(|_inner: &String| None)
.and(Some("new String".to_string()));