返回

rust-不能一次多次借用'x'作为可变项吗?

发布时间:2022-03-17 01:43:17 419

逻辑上,这段代码是正确的,但是rust不理解上下文。试图用很短的“独占引用生存期”从游标读取一些字节。

为什么这段代码不能编译?游戏场

struct Cursor {
    offset: usize,
    data: [u8; 4],
}
impl Cursor {
    fn read_slice(&mut self, n: usize) -> &[u8] {
        let data = &self.data[self.offset..self.offset + n];
        self.offset += n;
        data
    }
}
struct FooBar<'a> {
    foo: &'a [u8],
    bar: &'a [u8],
}

fn read_foobar_from<'a>(cursor: &'a mut Cursor) -> FooBar<'a> {
    FooBar {
        foo: cursor.read_slice(2),
        bar: cursor.read_slice(2),
    }
}

错误:

error[E0499]: cannot borrow `*cursor` as mutable more than once at a time
  --> src/main.rs:22:14
   |
19 |   fn read_foobar_from<'a>(cursor: &'a mut Cursor) -> FooBar<'a> {
   |                       -- lifetime `'a` defined here
20 | /     FooBar {
21 | |         foo: cursor.read_slice(2),
   | |              -------------------- first mutable borrow occurs here
22 | |         bar: cursor.read_slice(2),
   | |              ^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
23 | |     }
   | |_____- returning this value requires that `*cursor` is borrowed for `'a`
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
相关帖子