rust - 元组中的 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();
}
解决方案
默认情况下,当拳击时,它会作为你正在拳击的特定类型的盒子。在你的情况下是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());
}
}
推荐阅读
- selenium-chromedriver - 如何使用带硒的无头铬来滚动和单击元素?
- laravel - laravel 404(未找到)
- flutter - MissingPluginException(在通道 plugins.flutter.io/google_sign_in 上找不到方法 init 的实现)颤动发生
- java - 将 micronaut 应用程序 yml 文件作为 CLI arg 传递
- flutter - 如何双重解析字符串并将其舍入到 2 个小数位
- r - 在 R 中定义和分类单独的网络
- ruby-on-rails - 如何在基本字符串签名 OAuth1 中包含查询参数
- mongodb - 如果没有同名 mongoose 的文档,则创建新文档
- reactjs - 使用 AJAX 请求响应钩子
- c# - Visual Studio 输出窗口 - 控制输出的内容