我有一个基本的 Reader
封装了一些通用元素:
pub struct Reader<R> {
inner: R,
order: Endian,
first_ifd_offset: usize,
}
impl<R: Read + Seek> Reader<R> {
pub fn new(reader: R) -> Result<Reader<R>> {
let mut order_raw = [0, 0];
reader.read_exact(&mut order_raw)?;
let magic_number = u16::to_be(u16::from_bytes(order_raw));
/* ... */
}
}
这不会编译并产生以下错误:
error[E0596]: cannot borrow immutable argument `reader` as mutable
--> src/reader.rs:17:9
|
15 | pub fn new(reader: R) -> Result<Reader<R>> {
| ------ consider changing this to `mut reader`
16 | let mut order_raw = [0, 0];
17 | reader.read_exact(&mut order_raw)?;
| ^^^^^^ cannot borrow mutably
当我按值获取参数时,new
函数应该是 reader
元素的新所有者。编译器建议我在函数参数前添加一个 mut
关键字。
文档是否提到在函数参数前添加 mut
关键字的可能性?我找不到提及它的资源。
标准库的 BufReader
结构有一个
类似的 new
函数并且不使用 mut
关键字而是使用 unsafe
正文中的 block 代码。 unsafe
是否会阻止在函数签名中使用 mut
?
最佳答案
书中暗示但没有直接提及。 let
和函数参数都是模式,所以就像您可以在 let
中使用 mut
一样,您也可以在参数中使用它。
关于rust - 文档是否提到在函数参数前面添加 `mut` 关键字的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058998/