[Newbie] Need help extracting file name from string or str path


I’m trying to learn rust by doing a simple project that uploads a file to ftp server for which I need to extract the file name and I am having a hard time doing it the file_name method returns Option where as I need just the exact file name for now somewhat like “thisfile.zip” or “this_file.exe”

code sample:
let ancestors = Path::new(& _file_path).file_name();
println!(“File name was {:#?}”, ancestors);

output example:
File name was Some(

Desired output:
File name was devupload.exe

I’d be glad if someone can guide me through this

The current hacky way which i am currently using is

let _file_name = Path::new(& _file_path).file_name().unwrap().to_os_string().into_string().unwrap();

This works but I am not sure whether or not is it correct.


let ancestors = Path::new(& _file_path).file_name().unwrap();
println!("File name was {:?}", ancestors);

This should be better but it will print:

File name was "devupload.exe"

If you don’t want the quotes, this should work:

let ancestors = Path::new(& _file_path).file_name().unwrap().to_str().unwrap();
println!("File name was {}", ancestors);

Also in Rust a variable with an underscore as a first character means this variable won’t be used.


Thank you so much for your valuable response!

Just use println!("{}", ancestors.display()).