因为在 stable RustOsStr::display() 还是实验特性,只能在 nightly + feature gate 下用,所以编译不过

在 stable 里,应该用 to_string_lossy()to_str()

let fname = e.file_name()
    .to_string_lossy()   // 返回 Cow<str>
    .to_string();        // 转换成 String

或者(如果你确认文件名能保证是 UTF-8):

let fname = e.file_name()
    .to_str()
    .unwrap_or_default()
    .to_string();

区别

  • to_string_lossy():遇到非法 UTF-8 会自动替换为 ,安全无 panic。

  • to_str().unwrap():如果不是合法 UTF-8 会 panic。

  • to_str().unwrap_or_default():失败时返回空字符串。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐