当我编译这段代码时
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`
For more information about this error, try `rustc --explain E0499`.
error: could not compile `dns_self` due to previous error
但是,如果我将返回值从&str
修改为String
,则编译时不会出错.
有没有人能解释为什么我在返回&str
时会出错,但在返回String
时却不会?