簡體   English   中英

元組中的 Rust trait 對象 --- 預期的 trait 對象,找到的類型

[英]Rust trait object in tuple --- expected trait object, found type

我一直在閱讀The Rust Programming Language 的第 17 章,我一直在嘗試在我的代碼中使用 trait 對象。

有人可以解釋為什么函數test2不編譯而其他函數編譯嗎?

trait Print {
    fn print(&self) -> String;
}

impl Print for i32 {
    fn print(&self) -> String {
        return format!("{}", &self);
    }
}

impl Print for &str {
    fn print(&self) -> String {
        return format!("'{}'", &self);
    }
}

pub fn test1() {
    let mut v: Vec<(usize, Box<dyn Print>)> = Vec::new();
    let bxx = Box::new(0);
    let idx = 1;
    v.push((idx, bxx));
    
    for (idx, val) in &v {
        println!("{} - {}", idx, val.print());
    }
}

pub fn test2() {
    let mut v: Vec<(usize, Box<dyn Print>)> = Vec::new();
    let bxx = Box::new(0);
    let idx = 2;
    let t = (idx, bxx);
    v.push(t);
    
    for (idx, val) in &v {
        println!("{} - {}", idx, val.print());
    }
}

pub fn test3() {
    let mut v: Vec<(usize, Box<dyn Print>)> = Vec::new();
    v.push((3, Box::new("a")));
    
    for (idx, val) in &v {
        println!("{} - {}", idx, val.print());
    }
}




fn main() {

    test1();
    test2();
    test3();

}

操場

默認情況下,當拳擊時,它將作為您正在拳擊的特定類型的盒子。 在你的情況下是Box<i32> 如果您專門注釋類型,則它可以工作:

pub fn test2() {
    let mut v: Vec<(usize, Box<dyn Print>)> = Vec::new();
    let bxx: Box<dyn Print> = Box::new(0);
    let idx = 2;
    let t = (idx, bxx);
    v.push(t);
    
    for (idx, val) in &v {
        println!("{} - {}", idx, val.print());
    }
}

操場

暫無
暫無

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

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