一次不能多次借用“x”作为可变的吗?

发布于 2025-01-14 03:18:47 字数 1436 浏览 0 评论 0原文

从逻辑上讲,这段代码是正确的,但是 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`

Logically this code is correct, However rust doesn't understand the context. Trying to reading some byte from cursor with very short 'lifetime of exclusive reference.

Why this code does not compile? Playground

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:

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`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往昔成烟 2025-01-21 03:18:47

我作为评论链接的重复< /a> 解决了您收到此错误的原因。 (tl;dr:Rust 不会降级借用;一个函数可变地借用一个值并返回具有相同生命周期的不可变引用,导致可变借用与返回的引用一样存在。)

我们如何解决这个问题案件?

当我想到“光标”时,我不会想到“拥有数据并允许读取该数据的东西”,我想到的是“读取其他东西拥有的数据的东西”。事实证明,模型可以通过使用其他东西来绑定返回引用的生命周期来解决这个问题。

如果我们让 Cursor 借用数据而不是拥有它,我们可以表示返回的引用绑定到该数据的生命周期,而不是 的可变借用自我:

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

游乐场

如果你想要光标拥有数据然后内部可变性(例如offset: Cell)可能是您唯一的选择:

struct Cursor {
    offset: Cell<usize>,
    data: [u8; 4],
}
impl Cursor {
    fn read_slice(&self, n: usize) -> &[u8] {
        let offset = self.offset.get();

        let data = &self.data[offset..offset + n];
        self.offset.set(offset + n);
        data
    }
}

游乐场

The duplicate I linked as a comment addresses why you get this error. (tl;dr: Rust doesn't downgrade borrows; a function borrowing a value mutably and returning an immutable reference with the same lifetime causes the mutable borrow to exist as long as the returned reference does.)

How might we solve the problem in this case?

When I think "cursor" I don't think "something that owns data and allows reading that data out," I think "something that reads out data owned by something else." It turns out that model can solve this problem by having something else to tie the lifetime of the returned reference to.

If we make Cursor borrow the data instead of owning it, we can denote that the returned reference is bound to the lifetime of that data instead of the mutable borrow of self:

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

(Playground)

If you want Cursor to own the data then interior mutability (e.g. offset: Cell<usize>) may be your only option:

struct Cursor {
    offset: Cell<usize>,
    data: [u8; 4],
}
impl Cursor {
    fn read_slice(&self, n: usize) -> &[u8] {
        let offset = self.offset.get();

        let data = &self.data[offset..offset + n];
        self.offset.set(offset + n);
        data
    }
}

(Playground)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文