【问题标题】:Get the file name as a string in Rust在 Rust 中获取文件名作为字符串
【发布时间】:2020-09-06 14:23:21
【问题描述】:

我正在尝试使用以下代码获取给定字符串的文件名:

fn get_filename() -> Result<(), std::io::Error> {
    let file = "folder/file.text";
    let path = Path::new(file);
    let filename = path.file_name()?.to_str()?;
    println!("{}",filename);
    Ok(())
}

但我收到此错误:

error[E0277]: `?` couldn't convert the error to `std::io::Error`

原始代码不想返回Result,但这是使用? 的唯一方法。我该如何解决这个问题?

【问题讨论】:

    标签: error-handling rust compiler-errors path filenames


    【解决方案1】:

    根据 Niklas 的回答,答案如下:

    fn filename() -> Option<()> {
        let file = "hey.text";
        let path = Path::new(file);
        let filename = path.file_name()?.to_str()?;
        println!("{}",filename);
        None
    }
    

    【讨论】:

      【解决方案2】:

      .file_name().to_str() 在这里都返回一个 Option。在None 变体上使用? 运算符转换为Err 是一项实验性功能(请参阅the NoneError documentation)。如果您想使用? 运算符,可以考虑在此处返回Option&lt;()&gt; 或手动解包结果。

      【讨论】:

        猜你喜欢
        • 2015-11-25
        • 1970-01-01
        • 2010-12-06
        • 2013-08-27
        • 2023-03-04
        • 1970-01-01
        相关资源
        最近更新 更多