【问题标题】:How can a Rust trait object return another trait object?Rust 特征对象如何返回另一个特征对象?
【发布时间】:2020-02-10 01:34:21
【问题描述】:

如何在 Rust 中尝试类似以下的操作?

构建器类是一个特征对象,它返回另一个特征对象(类型擦除),其中选择的实现由我们正在使用的构建器特征的特定对象定义。

trait Builder {
    // I want this trait to return a trait object
    fn commits(&self) -> dyn Commit;

    fn finish(&self);
}

trait Commit {
}

struct FooBuilder {
}

struct FooCommit {
}

impl Builder for FooBuilder {
    fn commits(&self) -> impl Commit {
        FooCommit{ }
    }

    fn finish(&self) {
    }
}

fn get_commits(b: &Builder) {
    // trait object returns a trait
    let c = b.commits();
}

fn main() {
    let b = FooBuilder{};
    get_commits(&b);
    b.finish();
}

【问题讨论】:

  • 特征不是对象,它是对象的属性。你可以返回一些实现 trait 的东西。

标签: rust


【解决方案1】:

从 Rust 的 trait 方法返回 trait 对象没有问题:

trait Foo {
  fn bar(&self) -> Box<dyn Bar>;
}

需要注意的一点是,您需要返回Box&lt;dyn Bar&gt;,而不是dyn Bar,因为dyn Bar 的大小在编译时是未知的,这使得它毫无用处。

当你实现这个特征时,签名必须匹配,所以它应该返回Box&lt;dyn Bar&gt;,而不是impl Bar

impl Foo for MyFoo {
  fn bar(&self) -> Box<dyn Bar> {
    Box::new(MyBar{})
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2020-07-07
    • 2013-10-30
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多