Path
While paths can be represented as strings in Rust, we can use PathBuf
and Path
for code that is easier to maintain, and more reliable. The Path
type is helpful in many programs.
Some methods, like current_dir()
return a PathBuf
, which is a mutable path. We can handle PathBuf
as a Path
, and convert back into a PathBuf
with the to_path_buf()
function.
This program gets the current working directory, which is the active directory in a console window. And then it adds a directory to the PathBuf
, and then a file name.
current_dir()
we get a PathBuf
that contains the current working directory.push()
on a PathBuf
, we can add a directory. More than one directory can be added.PathBuf
to a function that requires a Path
reference.PathBuf
, which can be changed, from a Path
, we can use the to_path_buf()
method.push()
. We can place an extension on the end of the path if it is needed.str
from the PathBuf
(or Path
) we can use to_str()
. On the str
, we can get a String
by further calling to_string()
.use std::env; use std::path::*; fn main() { // Step 1: get a PathBuf from the env. let mut p = env::current_dir().unwrap(); // Step 2: add a directory. p.push("abc"); // Step 3: pass to a method as a Path. add_file_name(&p); } fn add_file_name(p: &Path) { // Step 4: convert the Path to a PathBuf so we can modify it. let mut f = p.to_path_buf(); // Step 5: add a file name. f.push("xyz.txt"); // Step 6: get a str, which we can use to open a file. let file_name = f.to_str().unwrap(); println!("{}", file_name); }C:\Users\mount\OneDrive\Documents\programs\hello-rust\abc\xyz.txt
Because Path
and PathBuf
provide helpful features, like handling delimiters in a cross-platform way, they are preferred when building up paths. They can reduce complexity.