如何返回实现给定特征的任何类型?

时间:2019-06-22 23:52:42

标签: rust

我们有以下代码:

enum Widgets {
    A,
    B,
}

trait Widget {}

struct A {}

impl A {
    fn new() -> Self {
        A {}
    }
}

impl Widget for A {}

struct B {}

impl B {
    fn new() -> Self {
        B {}
    }
}

impl Widget for B {}

struct Foo {
    widgets: Vec<Widgets>,
}

impl Foo {
    fn create_widget(self) -> impl Widget {
        match self.widgets[0] {
            Widgets::A => A::new(),
            Widgets::B => B::new(),
        }
    }
}

Playground link.

此代码无法编译,因为匹配臂具有不兼容的类型。但是它们都实现了特征Widget,并且我们的函数似乎在说我们将返回实现Widget的东西。

我们如何从匹配逻辑中返回实现Widget的任何类型?

0 个答案:

没有答案
相关问题