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?
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) ofself
.- if
path
has a prefix but no root, it replacesself
.
If you change your example to "js/main.js"
and then use join
, it will be properly constructed (playground)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With