Rust Path vs PathBuf
From Is working with Paths always this painful? on Reddit:
The difference between
PathBufis roughly the same as the one between
Pathonly holds a reference to the path string data but doesn’t own this data, while
PathBufowns the string data itself. This means that a
Pathis immutable and can’t be used longer than the actual data (held somewhere else) is available.
The reason why both types exists is to avoid allocations where possible. As most functions take both
PathBufas arguments (by using
AsRef<Path>for example), this usually doesn’t have a big impact on your code.
A very rough guide for when to use
- For return types:
- If your function gets passed a
Path[Buf]and returns a subpath of it, you can just return a
- If you create a new path, or combine paths or anything like that, you need to return a
- For arguments:
- Take a
PathBufif you need to store it somewhere.
- Use a
- In public interfaces, you usually don’t want to use
PathBufdirectly, but rather a generic
P: Into<PathBuf>. That way the caller can pass in