Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does joining paths completely replace the original path in Rust?

Tags:

rust

filepath

I don't understand how Rust concatenates file paths. Why doesn't this work:

fn main() {
    let root = std::path::Path::new("resources/");
    let uri = std::path::Path::new("/js/main.js");
    let path = root.join(uri);
    assert_eq!(path.to_str(), Some("resources/js/main.js"));
}

fails with:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `Some("/js/main.js")`,
 right: `Some("resources/js/main.js")`', src/main.rs:5:5

I see in the docs that "pushing an absolute path replaces the existing path", but this seems like a terrible idea that will catch a lot of people.

In that case, how do I safely strip the absolute path, or make it relative?

like image 547
Petrus Theron Avatar asked Nov 22 '18 11:11

Petrus Theron


1 Answers

This is because "/js/main.js" is treated as an absolute path (doc)

If path is absolute, it replaces the current path.

On Windows:

  • if path has a root but no prefix (e.g. \windows), it replaces everything except for the prefix (if any) of self.
  • if path has a prefix but no root, it replaces self.

If you change your example to "js/main.js" and then use join, it will be properly constructed (playground)

like image 116
hellow Avatar answered Nov 10 '22 20:11

hellow