How to specify type in field assigning with "?"?

I have a function fn natOrNone<U, E, F: FnOnce(i32) -> Result<U, E>>(n: i32, f: F) -> Result<Option<U>, E> and I am using it in SomeStruct { theField: natOrNone(0, |x| Ok(x))? } . Clearly, rustc could not know what type E is. But where should I put the type signature ::<Result<Option<i32>, MyError>? I tried some places like I normally do with function calls. All got grammar error.

This struct is created inside some function, and the ? operator is doing the early return from this function. So, this error type (or something it can be implicitly coerced to) must be in its signature.

Yes, the signature is there. The whole function (creating the struct) is:

impl FromStr for SomeStruct {
  type Err = MyError;
  fn from_str(s: &str) -> Result<Self, Self::Err> {
    Ok(SomeStruct { theField: natOrNone(0, |x| Ok(x))? })
  }
}

And the error is:
(under natOrNone) cannot infer type for E.

    Ok(SomeStruct { theField: natOrNone::<_, SomeE, _>(0, |x| Ok(x))? })
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.