Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert PathBuf to String

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}");
}

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading