I’m trying to convert a PathBuf to a String so it can be inserted into a panic!() message for debugging file not found errors in a CLI program (based on Chapter 12 in the Rust Book).
The current solutions on StackOverflow return Cow<str> when using env::current_dir().unwrap().to_string_lossy() or Option<&str> when using env::current_dir().unwrap().into_os_string().to_str().
These types cannot be fed to a panic!() macro and will throw a compiler error.
Here is the current code:
let args: Vec<String> = env::args().collect();
let cwd = env::current_dir().unwrap().into_os_string().to_str();
if args.len() < 3 {
panic!("Not enough arguments, give a query argument and a file path. Current working directory is {cwd}");
}
Currently I am trying to use an ‘if let’ statement with Option<&str> to extract the ‘&str’ but the borrow checker blocks me from using it:
let pwd: String;
if let Some(str) = cwd {
let pwd = str.into_string();
}
println!("{pwd}");
>Solution :
The idiomatic way to print a path in a user-facing way is to use Path::display:
let args: Vec<String> = env::args().collect();
let cwd = env::current_dir().unwrap();
if args.len() < 3 {
let cwd = cwd.display();
panic!("Not enough arguments, give a query argument and a file path. Current working directory is {cwd}");
}