相关疑难解决方法(0)

为什么链接生命周期只与可变引用有关?

前几天,有一个问题,如果有人有一个问题,一个可变引用其中包含借来的数据本身就是一种类型的连接寿命.问题是提供对类型的引用,借用与类型内部借用数据相同的生命周期.我试图重新创建问题:

struct VecRef<'a>(&'a Vec<u8>);

struct VecRefRef<'a>(&'a mut VecRef<'a>);

fn main() {
    let v = vec![8u8, 9, 10];
    let mut ref_v = VecRef(&v);
    create(&mut ref_v);
}

fn create<'b, 'a>(r: &'b mut VecRef<'a>) {
    VecRefRef(r);
}
Run Code Online (Sandbox Code Playgroud)

示例代码

'b在这里明确注释了create().这不编译:

error[E0623]: lifetime mismatch
  --> src/main.rs:12:15
   |
11 | fn create<'b, 'a>(r: &'b mut VecRef<'a>) {
   |                      ------------------
   |                      |
   |                      these two types are declared with different lifetimes...
12 |     VecRefRef(r);
   |               ^ ...but data from `r` flows …
Run Code Online (Sandbox Code Playgroud)

rust

15
推荐指数
2
解决办法
673
查看次数

标签 统计

rust ×1