简体   繁体   English

Rust trait 对象如何返回另一个 trait 对象?

[英]How can a Rust trait object return another trait object?

How can I attempt something like the following in Rust?如何在 Rust 中尝试类似以下的操作?

The builder class is a trait object which returns another trait object (type erasure) where the implementation that is selected is defined by the specific object of the builder trait that we are using. builder 类是一个 trait 对象,它返回另一个 trait 对象(类型擦除),其中选择的实现由我们正在使用的 builder trait 的特定对象定义。

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();
}

There is no problem returning trait objects from trait methods in Rust:从 Rust 中的 trait 方法返回 trait 对象没有问题:

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

One thing to notice is that you need to return Box<dyn Bar> , not dyn Bar , since size of dyn Bar is not known at compiled time, which renders it useless.需要注意的一件事是您需要返回Box<dyn Bar> ,而不是dyn Bar ,因为在编译时不知道dyn Bar大小,这使得它无用。

When you implement this trait, the signature has to match, so it should return Box<dyn Bar> , not impl Bar :当你实现这个特性时,签名必须匹配,所以它应该返回Box<dyn Bar> ,而不是impl Bar

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM