You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Rust中调用方法时需将File变量声明为mut?

为什么username_file必须声明为mut?

先看对应的Rust代码:

fn read_username_from_file() -> Result<String, io::Error> {
    let username_file_result = File::open("hello.txt");

    let mut username_file = match username_file_result {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut username = String::new();

    match username_file.read_to_string(&mut username) {
        Ok(_) => Ok(username),
        Err(e) => Err(e),
    }
}

原因很直接:

  • File类型的read_to_string方法签名为fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>,它要求接收一个可变的自身引用(&mut self)。
  • 这是因为读取文件的操作会修改File实例内部的状态,比如移动文件指针位置、更新已读取字节计数等,这些都是对实例内部数据的修改。
  • 在Rust规则中,要获取一个变量的可变引用,该变量本身必须被声明为mut,所以即便我们没有给username_file重新赋值,也得把它标记为可变,才能满足方法的调用要求。

内容的提问来源于stack exchange,提问作者Alan Sun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:14:54