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

当我将文件推送到PathBuf上时,为什么PathBuf会丢失当前目录?,path,rust,Path,Rust,当我将字符串推到路径上时,当前存储的部分目录似乎丢失了。例如,如果我这样做 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

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

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
有人知道为什么推送(路径)会从以下位置删除
\User\JohnDoe\Desktop\testfolder

如果
path
是绝对路径,则它将替换当前路径

在Windows上:

  • 如果
    path
    有根但没有前缀(例如
    \windows
    ),它将替换 除了
    self
    的前缀(如果有)之外的所有内容
  • 如果路径具有 前缀但没有根,它将替换
    self
您的示例属于第一个要点,其中它将
C:
以外的所有内容替换为
\test.txt


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

我假定它是
“\\test.txt”
“\test.txt”
的行为会有很大不同,将
\t
解释为HTAB。啊,我的错误是/test.txt刚刚修复了它