繁体   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