元组中的 Rust trait 对象 --- 预期的 trait 对象,找到的类型

标签 rust traits

我一直在阅读 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();

}
playground

最佳答案

默认情况下,在拳击时,它将作为您正在拳击的特定类型的盒子。在你的情况下是 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());
    }
}
Playground

关于元组中的 Rust trait 对象 --- 预期的 trait 对象,找到的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69746514/

相关文章:

function - 在 Rust 中,什么是 `fn() -> ()` ?

Scala:打印给定类的字段和值

regex - 如何通过 nom 解析匹配的分隔符?

rust - 捕获无法复制的移动值

rust - 如何使用 Serde 反序列化 parking_lot::Mutex?

scala - 选择特征来继承 Scala 中的通用方法

scala - 是否可以定义一个未命名的特征并将其用作 Scala 中的混合?

rust - "combine"两个选项有没有内置的方法?

rust - 每当 gtk 应用程序运行多次时,g_application_parse_command_line 中的断言就会失败

rust - 为什么盒装变量需要显式类型才能传递给函数?