< 返回版块

Yesifan 发表于 2021-07-29 17:00

可不可以简化成像这样

fn test() -> A {
    let c = b?;
    let s = do_something(c)?;
    A(s)

}

Ext Link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ce902b87f98eafdcf3bb42c83fc4a299

评论区

写评论
祐祐 2021-07-30 23:03

寫一寫就離題了,但後面的 match 可以參考

use MyOption::*;

trait TagStruct {}

enum MyOption<X: TagStruct, Y: TagStruct, Z: TagStruct> {
    ASome(X),
    BSome(Y),
    CSome(Z),
}

struct A(pub String);
struct B(pub String);
struct C(pub String);

impl TagStruct for A {}
impl TagStruct for B {}
impl TagStruct for C {}

type MyOptionABC = MyOption<A, B, C>;
type ResultABC<T> = Result<T, MyOptionABC>;

fn do_something(c: MyOptionABC) -> ResultABC<String> {
    // do something
    return match c {
        CSome(x) => {
            if &x.0 == "success" {
                Ok(x.0)
            } else {
                Err(CSome(x))
            }
        }
        _ => Err(c),
    };
}

fn test() -> ResultABC<MyOptionABC> {
    let data = C("c".to_string());
    let b = Ok(CSome(data));
    let c = b?;
    let s = do_something(c)?;
    Ok(ASome(A(s)))
}

fn Main() {
    let data = test();
    let data = match data {
        Ok(x) => match x {
            ASome(a) => a.0,
            _ => String::from("or B, C ..."),
        },
        Err(x) => match x {
            BSome(a) => a.0,
            CSome(a) => a.0,
            _ => String::from("or ... a"),
        },
    };
    println!("{}", data);
}
htqx 2021-07-29 20:06

fn test() -> A { let b: Result<C, B> = Ok(C("c".to_string())); let c: C = if let Ok(c) = b { c } else { panic!("err") }; let c: Result<String, C> = Err(c);

if let Ok(s) = c {
    A(s)
} else if let Err(c) = c {
    c.into()
} else {
    panic!("")
}

}

munpf 2021-07-29 19:44

map_or_else

b.map_or_else(A::from, |c| {
    do_something(c).map_or_else(A::from, A)
});
yuana1 2021-07-29 19:24

可通过如下方式简化

   b.map(|c|
        do_something(c).map(|e| A(e))
            .unwrap_or_else(|v| v.into()))
        .unwrap_or_else(|b| b.into())

? 返回的一定是Result类型的

1 共 4 条评论, 1 页