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

Rust error[E0716]:临时值提前释放问题求解(已尝试let绑定)

Rust E0716 报错解决:临时值提前释放问题

我之前查过Rust官方的E0716错误码文档,里面的问题和解答很有用,但我的情况不一样,所以来提问。

我要读取Ubuntu Linux 22.10系统ext4文件系统的目录条目,写了下面这段代码——我知道它不够符合Rust风格,但本来觉得能满足需求:

let mut all_chosenfiles: Vec<&str> = Vec::new();
for next_path in path_components {
    for next_dir_entry in fs::read_dir(next_path) {
        for next_file in next_dir_entry {
            let file_metadata = next_file.as_ref().unwrap().metadata().unwrap();
            if file_metadata.is_file()
                && file_metadata.mode() & 0o500 == 0o500 {
                    let chosen_file = next_file.unwrap().path();
                    all_chosenfiles.push(chosen_file.to_owned().to_str().unwrap());
            }

        }
    }
}

结果编译器报错了:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:31:46
   |
31 |                         all_chosenfiles.push(chosen_file.to_owned().to_str().unwrap());
   |                         ---------------------^^^^^^^^^^^^^^^^^^^^^^-------------------- temporary value is freed at the end of this statement
   |                         |                    |
   |                         |                    creates a temporary which is freed while still in use
   |                         borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

我明白报错的原因,也试着按照文档建议用let绑定来解决,修改后的代码是这样:

for next_path in path_components {
    for next_dir_entry in fs::read_dir(next_path) {
        for next_file in next_dir_entry {
            let file_metadata = next_file.as_ref().unwrap().metadata().unwrap();
            if file_metadata.is_file()
                && file_metadata.mode() & 0o500 == 0o500 {
                    let chosen_path = next_file.unwrap().path();
                    let chosen_file = &chosen_path.to_owned().to_str().unwrap();
                    all_chosenfiles.push(chosen_file);
            }

        }
    }
}

但编译器还是报错:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:31:44
   |
31 |                         let chosen_file = &chosen_path.to_owned().to_str().unwrap();
   |                                            ^^^^^^^^^^^^^^^^^^^^^^                  - temporary value is freed at the end of this statement
   |                                            |
   |                                            creates a temporary which is freed while still in use
32 |                         all_chosenfiles.push(chosen_file);
   |                                              ----------- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

我实在搞不懂,肯定是漏了某种Rust的惯用写法。难道只能用*运算符解引用(也就是*chosen_file)来解决吗?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:15:36