相关疑难解决方法(0)

如何匹配特质实现者

我有一个由某些结构实现的特征.我想写一个模式匹配,我可以处理每个可能的情况:

trait Base {}

struct Foo {
    x: u32,
}
struct Bar {
    y: u32,
}

impl Base for Foo {}
impl Base for Bar {}

fn test(v: bool) -> Box<Base + 'static> {
    if v {
        Box::new(Foo { x: 5 })
    } else {
        Box::new(Bar { y: 10 })
    }
}

fn main() {
    let f: Box<Base> = test(true);

    match *f {
        Foo { x } => println!("it was Foo: {}!", x),
        Bar { y } => println!("it was …
Run Code Online (Sandbox Code Playgroud)

rust

25
推荐指数
3
解决办法
5782
查看次数

标签 统计

rust ×1