Dumbapples
Dumbapples

Reputation: 4639

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

Part of the current directory stored seems to be lost when I push a string onto a path. For example, if I do...

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

I get outputs on the console similar to

C:\User\JohnDoe\Desktop\testfolder
C:\test.txt

Does anyone know why push(path) might be deleting \User\JohnDoe\Desktop\testfolder?

Upvotes: 2

Views: 456

Answers (1)

Scott Olson
Scott Olson

Reputation: 3542

From the 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.

Your example falls under the first bullet point, where it replaces everything but C: with \test.txt.

The solution is to use a non-absolute path, ie, test.txt.

Upvotes: 3

Related Questions