Philosophical question about PathBuf::push

#1

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?

0 Likes

#2

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.

0 Likes

#3

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.)

0 Likes

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

See Path::join

5 Likes

#5

Helpful, thank you.

1 Like