相关疑难解决方法(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
查看次数

如何修改作为函数参数的切片?

参数可以传递给函数并修改:

fn set_42(int: &mut i32) {
    *int += 42;
}

fn main() {
    let mut int = 0;
    set_42(&mut int);
    println!("{:?}", int);
}
Run Code Online (Sandbox Code Playgroud)

输出:

42
Run Code Online (Sandbox Code Playgroud)

天真地改变代码以使用切片失败了一大堆错误:

fn pop_front(slice: &mut [i32]) {
    *slice = &{slice}[1..];
}

fn main() {
    let mut slice = &[0, 1, 2, 3][..];
    pop_front(&mut slice);
    println!("{:?}", slice);
}
Run Code Online (Sandbox Code Playgroud)

输出:

<anon>:2:14: 2:27 error: mismatched types:
 expected `[i32]`,
    found `&[i32]`
(expected slice,
    found &-ptr) [E0308]
<anon>:2     *slice = &{slice}[1..];
                      ^~~~~~~~~~~~~
<anon>:2:14: 2:27 help: see the detailed explanation …
Run Code Online (Sandbox Code Playgroud)

rust

6
推荐指数
2
解决办法
1591
查看次数

标签 统计

rust ×2