我有一段无法编译的代码:
impl BytePacketBuffer {
fn read(&mut self) -> Result<u8, &str> {
if self.pos >= 512 {
return Err("End of buffer".into());
}
let res = self.buf[self.pos];
self.pos += 1;
Ok(res)
}
fn read_u16(&mut self) -> Result<u16, &str> {
let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
Ok(res)
}
}
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/byte_packet_buffer.rs:53:51
|
52 | fn read_u16(&mut self) -> Result<u16, &str> {
| - let's call the lifetime of this reference `'1`
53 | let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
| ------------ ^^^^^^^^^^^ second mutable borrow occurs here
| |
| first mutable borrow occurs here
| returning this value requires that `*self` is borrowed for `'1`
但如果我将返回类型从&str
修改为String
,它可以编译通过而没有错误。有人能解释一下为什么返回&str
会出错,而返回String
不会吗?
?
解糖的NLL案例#3。让我们用Polonius测试一下...是的。它在Polonius中可以工作。 - Chayim Friedman