首页 > 解决方案 > 元组中的 Rust 特征对象 --- 预期的特征对象,找到的类型

问题描述

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

}

操场

标签: rusttraits

解决方案


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

操场


推荐阅读