Philosophical question about PathBuf::push


Why does PathBuf::push(Path) not return self?

Means I could say let p = PathBuf::from("/my/funky/path").push(self.get_some_more_funk())

I can put that in a confditional like:
if PathBuf::from("/my/funky/path").push(self.get_some_more_funk()).exist()

What point about language design am I missing?



I can’t really say why it was designed a certain way, but: if it was going to do this it would also consume self and return it again. Or it could take &self and clone it to explicitly return a new path, so you could have a base_dir object and generate paths off it for various files. Currently it just mutates state of the original object.

This would be more like a builder pattern, and might be chosen if it was being designed today.



Technically it’s library design.

But generally, edit-in-place stuff isn’t designed for chaining. Like for the equivalent on String you’d be using +, not push_str.

(Boost overloads / for this, iirc, so its equivalent would be if (Path::from("/my/funky/path") / self.get_some_more_funk()).exist(), but I don’t know if that would be considered un-rusty if proposed.)


if Path::from("/my/funky/path").join(self.get_some_more_funk()).exists() 

See Path::join



Helpful, thank you.

1 Like