Search code examples
error-handlingrustcompiler-errorspathfilenames

Get the file name as a string in Rust


I am trying to get the file name of a given string using the following code:

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(())
}

But I get this error:

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

The original code didn't want to return Result, but that's the only way to use ?. How can I fix this?


Solution

  • Based on Niklas's answer here is the answer:

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