不能一次多次借用可变的"x"

  • 本文关键字:quot 一次 不能 rust lifetime
  • 更新时间 :
  • 英文 :


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

我作为注释链接的重复项说明了为什么会出现此错误。(太长了,读不下去了:Rust不会降级借用;一个函数可变地借用一个值,并返回一个具有相同生存期的不可变引用,这会导致可变借用与返回的引用一样存在。(

在这种情况下,我们该如何解决这个问题?

当我想到";光标";我不认为;拥有数据并允许读取该数据的东西;我认为"读出其他人拥有的数据的东西"事实证明,模型可以通过将返回引用的生存期与其他东西联系起来来解决这个问题

如果我们让Cursor借用数据而不是拥有它,我们可以表示返回的引用绑定到该数据的生存期,而不是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
}
}

(游乐场(

如果您希望Cursor拥有数据,那么内部可变性(例如offset: Cell<usize>(可能是您唯一的选择:

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
}
}

(游乐场(

最新更新