Path Struct in Rust Programming


Path struct in Rust is used to represent the file paths in the underlying filesystem. It should also be noted that a Path in Rust is not represented as a UTF-8 string; instead, it is stored as a vector of bytes (Vec<u8>).

Example

Consider the example shown below −

 Live Demo

use std::path::Path;

fn main() {
   // Create a `Path` from an `&'static str`
   let path = Path::new(".");
   // The `display` method returns a `Show`able structure
   let display = path.display();
   // Check if the path exists
   if path.exists() {
      println!("{} exists", display);
   }
   // Check if the path is a file
   if path.is_file() {
      println!("{} is a file", display);
   }
   // Check if the path is a directory
   if path.is_dir() {
      println!("{} is a directory", display);
   }
   // `join` merges a path with a byte container using the OS specific
   // separator, and returns the new path
   let new_path = path.join("a").join("b");
   // Convert the path into a string slice
   match new_path.to_str() {
      None => panic!("new path is not a valid UTF-8 sequence"),
      Some(s) => println!("new path is {}", s),
   }
}

Output 

If we run the above code, we will see the following output −

. exists
. is a directory
new path is ./a/b

Updated on: 03-Apr-2021

346 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements