DEV Community


Posted on

Day34:Common Path Operations - 100DayOfRust

Common Path Operations:

use std::path::Path;

fn main() {
    let currdir = Path::new("./");

    // canonicalize return absolute path
    let absdir = currdir.canonicalize().unwrap();
    println!("Absolute path: {}", absdir.to_str().unwrap());

    // parent return parent path
    let pdir = absdir.parent().unwrap();
    println!("Parent path: {}", pdir.to_str().unwrap());

    // join to join sub path
    let toml = currdir.join("Cargo.toml");
    println!("Cargo.toml path: {:?}", toml);

    // is_file return if it is regular file; 
    // is_dir return if it is directory
    println!("Cargo.toml is file: {}", toml.is_file());

    // extension return file's extension
    println!("Cargo.toml extension: {:?}", toml.extension().unwrap());

    // is_relative return if path is relative path
    // is_absolute return if path is absolut path
    println!("Cargo.toml path is relative: {:?}", toml.is_relative());

    // starts_with return if path starts with xxx
    println!("Cargo.toml start with /home: {:?}", toml.starts_with("/home"));

    // strip_prefix remove path's prefix
    println!("Cargo.toml strip prefix: {:?}", toml.strip_prefix("./").unwrap());

Enter fullscreen mode Exit fullscreen mode


Absolute path: /home/bo/project/rust/pathtest
Parent path: /home/bo/project/rust
Cargo.toml path: "./Cargo.toml"
Cargo.toml is file: true
Cargo.toml extension: "toml"
Cargo.toml path is relative: true
Cargo.toml start with /home: false
Cargo.toml strip prefix: "Cargo.toml"
Enter fullscreen mode Exit fullscreen mode


Top comments (0)