我一直在阅读 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/