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

I don't have a Windows machine right now, but I want to make my cross-platform code. I have working code from build.rsthat 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")
+4
source share
2 answers

β€œGood enough” is a tough question. Both of them work to determine the path, because Windows treats slashes ( /) in the same way as backslashes ( \).

, - ( !), :

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

, , :

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
+5

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

:

fn main() {
    let path = Path::new("test/add_folder/hello.txt");

    let mut file = File::create(path).unwrap();
    file.write_all(b"Hello, world!").unwrap();
}

Windows, .


-

C:\Users\JohnDoe

/c/users/johndoe , c:/users/johndoe.

+3

Source: https://habr.com/ru/post/1681954/


All Articles