Get the file name as a string in Rust

Viewed 2524

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?

2 Answers

Both .file_name() and .to_str() here return an Option. The usage of the ? operator on the None variant to convert to an Err is an experimental feature (see the NoneError documentation). If you want to use the ? operator, you could consider returning Option<()> here or unwrapping the result by hand.

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
}
Related