gpt4 book ai didi

rust - 为什么连接路径会完全替换 Rust 中的原始路径?

转载 作者:行者123 更新时间:2023-11-29 07:58:00 24 4
gpt4 key购买 nike

我不明白 Rust 如何连接文件路径。为什么这不起作用:

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"));
}

失败:

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

我在 the docs 中看到“插入绝对路径取代现有路径”,但这似乎是一个会吸引很多人的糟糕想法。

在那种情况下,我该如何安全地剥离绝对路径,或使其成为相对路径?

最佳答案

这是因为 "/js/main.js" 被视为绝对路径 ( 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.

如果您将示例更改为 "js/main.js" 然后使用 join,它将被正确构造 (playground)

关于rust - 为什么连接路径会完全替换 Rust 中的原始路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53430401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com