简体   繁体   English

Rust 依赖将 trait 的实现注入到另一个对象中

[英]Rust dependency inject implementation of trait into another object

In Rust, I am trying to create an object of type Installer and pass a DownloaderFoo or DownloaderBar to its constructor ( playground ):在 Rust 中,我试图创建一个Installer类型的对象,并将DownloaderFooDownloaderBar传递给它的构造函数( playground ):

pub trait Downloader {
    fn run(&self);
}

pub struct DownloaderFoo;
impl Downloader for DownloaderFoo {
    fn run(&self)  {
        println!("DownloaderFoo::run");
    }
}

pub struct DownloaderBar;
impl Downloader for DownloaderBar {
    fn run(&self)  {
        println!("DownloaderBar::run");
    }
}

pub struct Installer {
    downloader: Downloader,
}

impl Installer {
    pub fn run(&self) {
        self.downloader.run();
        println!("Installer::run");
    }
}

fn main() {
    Installer{downloader: DownloaderFoo{}}.run();
    Installer{downloader: DownloaderBar{}}.run();
}

I get the following compile error:我收到以下编译错误:

   Compiling playground v0.0.1 (/playground)
warning: trait objects without an explicit `dyn` are deprecated
  --> src/main.rs:20:17
   |
20 |     downloader: Downloader,
   |                 ^^^^^^^^^^ help: use `dyn`: `dyn Downloader`
   |
   = note: `#[warn(bare_trait_objects)]` on by default

error[E0308]: mismatched types
  --> src/main.rs:30:27
   |
30 |     Installer{downloader: DownloaderFoo{}}.run();
   |                           ^^^^^^^^^^^^^^^ expected trait object `dyn Downloader`, found struct `DownloaderFoo`
   |
   = note: expected trait object `(dyn Downloader + 'static)`
                    found struct `DownloaderFoo`

I tried using dyn Downloader in the Installer members, but I'm a bit stuck and don't know how to move forward.我尝试在Installer成员中使用dyn Downloader ,但我有点卡住了,不知道如何前进。

Any ideas here?这里有什么想法吗? Thank you!谢谢!

The issue is that dyn Downloader does not have a size known at compile time.问题是dyn Downloader在编译时没有已知的大小。 You can fix this by wrapping it in a Box , which is pointer to an object on the heap:您可以通过将其包装在Box来解决此问题,该Box是指向堆上对象的指针:

pub struct Installer {
    downloader: Box<dyn Downloader>,
}

And inject the Downloaders like so:并像这样注入下载器:

fn main() {
    Installer{downloader: Box::new(DownloaderFoo{})}.run();
    Installer{downloader: Box::new(DownloaderBar{})}.run();
}

For more information about the Sized trait, see What does “Sized is not implemented” mean?有关Sized特征的更多信息,请参阅“未实现 Sized”是什么意思?

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

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