convert pathbuf to path in rust

In Rust, to convert a PathBuf into a Path, simply use the .as_path() method.

main.rs
use std::path::{Path, PathBuf};

fn main() {
    let path_buf = PathBuf::from("example.txt");
    let path = path_buf.as_path();
    println!("{:?}", path);
}
159 chars
8 lines

In the code above, we create a PathBuf variable path_buf and assign it the value of example.txt.

We then get a reference to the Path representation of the PathBuf object by calling .as_path() on it, and store it in the variable path.

The code then prints out the Path object using println! and the {:?} format specifier.

This will output:

main.rs
"example.txt"
14 chars
2 lines

Note: The as_path() method only returns a reference to the Path object, and does not allocate memory for a new copy of the path.

related categories

gistlibby LogSnag