在monad管道中使用into()

and*_*y g 3 monads types rust

我基本上试图在管道内转换一个值,如下所示:

#[derive(PartialEq)]
enum MyType { A, B }

impl Into<MyType> for i32 {
    fn into(self) -> MyType {
        match self {
            0 => MyType::A,
            _ => MyType::B
        }
    }
}

fn main() {
    let a: Result<i32, ()> = Ok(0);
    a.map(|int| int.into())
        .and_then(|enm| if enm == MyType::A { println!("A"); });
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是map()不知道它应该输出哪种类型.

我试过的其他东西不起作用:

a.map(|int| if int.into() as MyType == MyType::A { println!("A"); });

a.map(|int| int.into::<MyType>())
        .and_then(|enm| if enm == MyType::A { println!("A"); });
Run Code Online (Sandbox Code Playgroud)

这确实有效,但感觉不必要的复杂:

a.map(|int| {
    let enm: MyType = int.into();
    if enm == MyType::A { println!("A"); }
});
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

oli*_*obk 6

你不应该实现Into,你应该实现From,它会自动给你一个Intoimpl.然后你可以打电话a.map(MyType::from),一切正常:

impl From<i32> for MyType {
    fn from(i: i32) -> MyType {
        match i {
            0 => MyType::A,
            _ => MyType::B
        }
    }
}

fn main() {
    let a: Result<i32, ()> = Ok(0);
    a.map(MyType::from)
        .and_then(|enm| if enm == MyType::A { Err(()) } else { Ok(enm) } );
}
Run Code Online (Sandbox Code Playgroud)

或者你可以打电话a.map(Into::<MyType>::into),但这相当冗长.这是From/ Into二元性的原因,它在模块文档中进行了解释std::convert