[英]Why an immutable reference can work in match when mutable reference is required by function in Rust?
Hi I'm currently reading The Rust Programming Language book.嗨,我目前正在阅读Rust 编程语言书。 In error handling chapter I found this code works well:
在错误处理章节中,我发现这段代码运行良好:
fn read_username_from_file() -> Result<String, io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
However, after rewritting using ?
但是,改写后使用
?
operator, the code only works in this way:运算符,代码只能以这种方式工作:
fn read_username_from_file() -> Result<String, io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
Please note that f
now become mutable!请注意
f
现在变得可变了! In the first version f
is immutable.在第一个版本中
f
是不可变的。 The definition of read_to_string
is fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
, which requires a mutable self
reference. read_to_string
的定义是fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
,它需要一个可变的self
引用。 But why the first version works without an compile time error here?但是为什么第一个版本在这里没有编译时错误?
f
( self
) is not mutable here! f
( self
) 在这里是不可变的!
In the first version, the first f
is immutable, but then you shadow it and bind f
mutably:在第一个版本中,第一个
f
是不可变的,但随后您将其遮蔽并可变地绑定f
:
fn read_username_from_file() -> Result<String, io::Error> {
let f = File::open("hello.txt"); // this is immutable
let mut f = match f { ... } // this is mutable
}
The read_to_string
function takes a mutable reference to self
, so in both examples, f
is required to be mutable. read_to_string
function 对self
进行可变引用,因此在这两个示例中, f
都必须是可变的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.