2

I am trying to implement std::convert::TryFrom<OutputMessage> for warp::filters::ws::Message where OutputMessage is a simple struct that can be serialized with serde_json::to_string():

impl TryFrom<OutputMessage> for Message {
    type Error = ();

    fn try_from(output_message: OutputMessage) -> Result<Self, <Self as TryFrom<Message>>::Error> {
        match serde_json::to_string(&output_message) {
            Ok(output_string) => Ok(Message::text(output_string)),
            Err(err) => {
                return Err(());
            }
        }
    }
}

However, I'm getting the following errors for the function signature:

method `try_from` has an incompatible type for trait
expected fn pointer `fn(protocol::Output) -> Result<_, ()>`
found fn pointer `fn(protocol::Output) -> Result<_, Infallible>`

And this one for the returned Err(()):

mismatched types
expected enum `Infallible`, found `()`

Is there any way to make this implementation work, maybe by changing it's Error type? Or is this kind of trait implementation not really possible?

lsgng
  • 465
  • 8
  • 22
  • 3
    Try changing the return type to `Result`. The current return type is wrong because it specifies the `Error` associated type of `TryFrom`, which is different from the unit type you used for `Error`. – user4815162342 Mar 04 '21 at 11:51
  • @user4815162342 but `Error` is set to `()`, I would expect this to still work, no? – Ibraheem Ahmed Mar 04 '21 at 14:31
  • 3
    `Self::Error` (i.e. `TryFrom::Error`) is indeed `()`, but you were using `TryFrom::Error`, which is not the same as `TryFrom::Error`. As `Self` is `Message`, `TryFrom` is [automatically implemented](https://doc.rust-lang.org/std/convert/trait.TryFrom.html#generic-implementations) and returns `Ok(value)`. Also, since `TryFrom for T` cannot fail, the error variant of the conversion result is defined as `Infallible`. – user4815162342 Mar 04 '21 at 14:58

0 Answers0