< 返回版块

tch1121 发表于 2022-03-17 02:07

开始学rust 很多东西不懂 是和生命周期有关系码

fn main() {
  let items: ReadDir = read_dir(".").unwrap();

  for item in items {
    if let Ok(curr) = item {
      let name: &str = curr.file_name().to_str().unwrap();
      // 打印会报错
      eprintln!("{}", name);
    }
  }
}

评论区

写评论
viruscamp 2022-03-17 14:42
  1. 说清楚到底是编译错误还是运行错误。你说的给人感觉是运行错误。最好贴出错误详情。

  2. 你这个是 rust 最常见的临时变量超生命期借用编译错误,编译器已经告诉你了:

   Compiling playground v0.0.1 (/playground)
error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:8:24
   |
8  |       let name: &str = curr.file_name().to_str().unwrap();
   |                        ^^^^^^^^^^^^^^^^                  - temporary value is freed at the end of this statement
   |                        |
   |                        creates a temporary which is freed while still in use
9  |       // 打印会报错
10 |       eprintln!("{}", name);
   |                       ---- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

For more information about this error, try `rustc --explain E0716`.
error: could not compile `playground` due to previous error

波浪线标出的curr.file_name()是超范围借用的临时变量,只要给他一个变量名就好

use std::fs::read_dir;
use std::fs::ReadDir;
fn main() {
  let items: ReadDir = read_dir(".").unwrap();

  for item in items {
    if let Ok(curr) = item {
      let z = curr.file_name();
      let name: &str = z.to_str().unwrap();
      // 打印会报错
      eprintln!("{}", name);
    }
  }
}
SomeOne 2022-03-17 11:01

我个人理解是引用给了name,name又会在if这个作用域内结束自己的生命,所以报错了。

SomeOne 2022-03-17 09:35
fn main() {
    let items: ReadDir = read_dir(".").unwrap();
  
    for item in items {
      if let Ok(curr) = item {
        // 打印会报错
        eprintln!("{}", curr.file_name().to_str().unwrap());
      }
    }
}
1 共 3 条评论, 1 页