编者注:此代码示例来自1.0之前的Rust版本,并且在语法上不是有效的Rust 1.0代码.此代码的更新版本会产生不同的错误,但答案仍包含有价值的信息.
无论Box有没有生命,我都试过这个:
trait TraitToImpl {
fn do_something(self, val: i32);
}
struct Cont {
value: i32,
}
impl TraitToImpl for Cont {
fn do_something(self, val: i32) {
println!("{}", val);
}
}
struct StoreTrait<'a> {
field: Box<TraitToImpl + 'a>,
}
fn main() {
let cont = Box::new(Cont { value: 12 }) as Box<TraitToImpl>;
let a = StoreTrait { field: cont };
a.field.do_something(123);
}
Run Code Online (Sandbox Code Playgroud)
我得到的只是这个错误:
error: cannot convert to a trait object because trait `TraitToImpl` is not object-safe
我是生锈的新人,不明白一刻:
指针指南说:"你真的不应该返回指针".我没关系,但在我的HelloWorld程序中,我试图返回&str.我不需要盒装字符串,只需要&str立即打印它.我成功地在这个挑战中,但只是部分地.
所以,问问自己:
为什么我能做到
fn foo(p: &[uint]) -> &str { "STRING" }
Run Code Online (Sandbox Code Playgroud)
,但不能做
fn foo(p: Vec<uint>) -> &str { "STRING" } //error: missing lifetime specifier [E0106]
Run Code Online (Sandbox Code Playgroud)
,但仍然可以做
fn foo(p: Vec<uint>) -> &'static str { "STRING" }
Run Code Online (Sandbox Code Playgroud)
什么改变了从切片切换到Vec的事实?
PS抱歉我的假英语和假问题.我想,我只是没有得到一个生锈的借用者