Convert generic tuple to Result(value, _), (when there is no possible error)

Viewed 49

Okay so I'm using a library which is ffi and uses C, for whatever reason when I'm getting an iterator of values from one of the libraries functions the function never fails but returns some wrong stuff if it does fail. I've already dealt with all the checks to make sure what the user (of this api) is iterating over is correct information or no/less information (if some of its wrong) but i need to wrap all the values of the iterator to a Result even though this library isn't returning options or results so that it works with a bunch of other code (this is a generic trait I'm implementing).

  • I tried taking my iterator and using .map(|res| Ok(res)) however this does not work because the compiler cannot infer the type for e.

  • I have also tried using Result<_,_> like .map(|res| Result<res, _>) but apparently this is not an expression

  • Slight modification to the last one i also tried .map(|res| new: Result<res, _>) however then the result is non mutable while res is and it once again fails.

So I'm not really sure what to do here. I would really prefer the mapping of all the values to be inline and the error can be anything because there will never be a meaningful error however i still need a Result object for my generic trait.

P.S. im not sure if it will help but the type of res is (alloc::boxed::Box<[u8]>, alloc::boxed::Box<[u8]>).

1 Answers

As the error type, I'd use std::convert::Infallible, because that's what it's for: "The error type for errors that can never happen.".

For specifying the error type, the turbofish syntax (see bottom of this page, e.g.) is probably the most appropriate. There are several ways you could use it:

  • .map(|res| Ok::<_, Infallible>(res))
  • .map(|res| Result::<_, Infallible>::Ok(res))
  • or, as the eta-reduced variant .map(Ok::<_, Infallible>)

Alternatively, you can

  • use the syntax for specifying the return type of your closure:
    .map(|res| -> Result<_, Infallible> { Ok(res) }).
  • use as: .map(|res| Ok(res) as Result<_, Infallible>)

Note that the diffference between these is that Result::<_, Infallible>::Ok is a value (a constructor function, but functions are values), but Result<_, Infallible> is a type. Further note that the _ is a placeholder for a type, not some magic for a value/parameter (The syntax in your question looks awfully Scala-y, so I wanted to make clear that these are completely different.) You can replace the _ by (Box<[u8]>, Box<[u8]>), if you want.

Playground

Related