Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Path::new(many-subdirs) good enough for both Linux and Windows?

I have no Windows machine right now, but I want to make my code cross-platform. I have working code from build.rs that works on Linux:

Path::new("dir1/dir2/dir3")

Is this correct for Windows or should I use something like:

Path::new("dir1").join("dir2").join("dir3")
like image 272
user1244932 Avatar asked Jan 30 '23 23:01

user1244932


1 Answers

"Good enough" is a tricky question. Both of them work to identify a path because Windows treats forward slashes (/) the same as backwards slashes (\).

However, if you ever show the path to your user (remember about error messages too!), then you should strive to meet the expectations of the platform:

use std::path::Path;

fn main() {
    let p = Path::new("target/debug");
    println!("{}", p.exists());
    println!("{}", p.display());

    let p = Path::new("target").join("debug");
    println!("{}", p.exists());
    println!("{}", p.display());
}
true
target/debug
true
target\debug

Additionally, if you were to build on another path, mixing the two styles looks really bad:

fn main() {
    let cwd = std::env::current_dir().expect("No CWD");

    let p = cwd.join("target/debug");
    println!("{}", p.exists());
    println!("{}", p.display());

    let p = cwd.join("target").join("debug");
    println!("{}", p.exists());
    println!("{}", p.display());
}
true
c:\Rust\dirs\target/debug
true
c:\Rust\dirs\target\debug
like image 115
Shepmaster Avatar answered Feb 03 '23 12:02

Shepmaster