我正在阅读Rust书的生命周章,我在这个例子中看到了命名/显式生命周期:
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!("{}", x); // |
} // -+ x goes out …Run Code Online (Sandbox Code Playgroud) 我有各种结构,都实现相同的特征.我想在某些条件下进行分支,在运行时决定实例化哪些结构.然后,无论我遵循哪个分支,我都想从该特征中调用方法.
这可能在Rust吗?我希望实现类似下面的内容(不编译):
trait Barks {
fn bark(&self);
}
struct Dog;
impl Barks for Dog {
fn bark(&self) {
println!("Yip.");
}
}
struct Wolf;
impl Barks for Wolf {
fn bark(&self) {
println!("WOOF!");
}
}
fn main() {
let animal: Barks;
if 1 == 2 {
animal = Dog;
} else {
animal = Wolf;
}
animal.bark();
}
Run Code Online (Sandbox Code Playgroud) 我在迭代器上应用了一个闭包,我想使用stable,所以我想返回一个盒装Iterator.这样做的显而易见的方法如下:
struct Foo;
fn into_iterator(myvec: &Vec<Foo>) -> Box<dyn Iterator<Item = &Foo>> {
Box::new(myvec.iter())
}
Run Code Online (Sandbox Code Playgroud)
这是失败的,因为借用检查器无法推断出适当的生命周期.
经过一番研究,我找到了正确的方法来返回迭代器?,这让我想补充一下+ 'a:
fn into_iterator<'a>(myvec: &'a Vec<Foo>) -> Box<dyn Iterator<Item = &'a Foo> + 'a> {
Box::new(myvec.iter())
}
Run Code Online (Sandbox Code Playgroud)
但我不明白