Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
Amin Avatar asked Sep 16 '25 20:09

Amin


1 Answers

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
}
like image 101
Amin Avatar answered Sep 18 '25 17:09

Amin