元组中的 Rust 特征对象 --- 期望的特征对象,找到的类型
Rust trait object in tuple --- expected trait object, found type
我一直在阅读 The Rust Programming Language 中的第 17 章,并且一直在尝试在我的代码中使用特征对象。
有人能解释一下为什么函数 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());
}
}
我一直在阅读 The Rust Programming Language 中的第 17 章,并且一直在尝试在我的代码中使用特征对象。
有人能解释一下为什么函数 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());
}
}