簡體   English   中英

Rust 依賴將 trait 的實現注入到另一個對象中

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

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

我收到以下編譯錯誤:

   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`

我嘗試在Installer成員中使用dyn Downloader ,但我有點卡住了,不知道如何前進。

這里有什么想法嗎? 謝謝!

問題是dyn Downloader在編譯時沒有已知的大小。 您可以通過將其包裝在Box來解決此問題,該Box是指向堆上對象的指針:

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

並像這樣注入下載器:

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

有關Sized特征的更多信息,請參閱“未實現 Sized”是什么意思?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM