types - 在 monad 管道中使用 into()

标签 types rust monads

我基本上是想像这样在管道内转换一个值:

#[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"); });
}

我遇到的问题是 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"); });

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

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

有更好的方法吗?

最佳答案

你不应该实现 Into ,你应该实现 From , 它会自动给你一个 Into暗示。然后你可以调用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) } );
}

或者您可以调用 a.map(Into::<MyType>::into) ,但这相当冗长。 From 是有原因的/Into对偶性,在 std::convert module docs 中有解释

关于types - 在 monad 管道中使用 into(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837710/

相关文章:

postgresql - 从函数返回的自定义类型的意外行为

c# - 将类型本身而不是实例保存在字典中

java - Eclipse AST Java 模型 : Where in ICompilationUnit stored whether it is class, 接口(interface)或枚举?

parsing - 使用 Free Monad 实现词法分析器

scala - 类型投影别名因类型限制而失败

rust - 单位类型实现了哪些特征?

rust - `dyn` 和泛型有什么区别?

parsing - 最小纯应用解析器

haskell - Pipes-2.1.0 包中的最终确定

pointers - Rust 如何实现仅编译时指针安全?