相关疑难解决方法(0)

为什么Rust需要明确的生命周期?

我正在阅读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)

static-analysis reference lifetime rust

183
推荐指数
7
解决办法
2万
查看次数

是否允许多态变量?

我有各种结构,都实现相同的特征.我想在某些条件下进行分支,在运行时决定实例化哪些结构.然后,无论我遵循哪个分支,我都想从该特征中调用方法.

这可能在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)

rust

14
推荐指数
3
解决办法
655
查看次数

为什么需要使用plus运算符(Iterator <Item =&Foo> +'a)为特征添加生命周期?

我在迭代器上应用了一个闭包,我想使用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)

但我不明白

  • 这是做什么的
  • 为什么需要这里呢

lifetime rust

13
推荐指数
1
解决办法
761
查看次数

标签 统计

rust ×3

lifetime ×2

reference ×1

static-analysis ×1