为什么当我将文件推送到 PathBuf 上时,PathBuf 会丢失当前目录?

Why does PathBuf lose the current directory when I push a file onto it?

当我将字符串推入路径时,当前存储的部分目录似乎丢失了。例如,如果我这样做...

let mut path = "/test.txt";
let mut localpath = env::current_dir().unwrap();
println!("{}", localpath.display());
localpath.push(path);
println!("{}", localpath.display());

我在控制台上得到类似于

的输出
C:\User\JohnDoe\Desktop\testfolder
C:\test.txt

有谁知道为什么 push(path) 可能会删除 \User\JohnDoe\Desktop\testfolder

来自docs

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.

您的示例属于第一个要点,它将 C: 以外的所有内容替换为 \test.txt

解决方法是使用非绝对路径,即test.txt