Home
Rust
Path Example (to_path_buf)
Updated Dec 2, 2024
Dot Net Perls
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.
PathBuf
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.
Example. 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.
Step 1 With the env method current_dir() we get a PathBuf that contains the current working directory.
Step 2 With push() on a PathBuf, we can add a directory. More than one directory can be added.
Step 3 We can pass a reference to a PathBuf to a function that requires a Path reference.
Step 4 To convert back into a PathBuf, which can be changed, from a Path, we can use the to_path_buf() method.
Step 5 To add a file name, we can use push(). We can place an extension on the end of the path if it is needed.
Step 6 To get a 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 2, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen