Why does Path::new() return a reference while Vec::new() returns a value?


I’m new to Rust, and I come from C/C++. If I understand borrowing correctly, a reference implies a temporary transfer of ownership within a scope, while moving implies a permanent transfer of ownership.

Now, Vec::new() -> Vec<T> makes sense. I created a Vec, I own it now.

Why does Path::new() -> &Path ? Wouldn’t I want to own the value once I’ve created it instead of getting a reference?


The Path is a (readonly) slice (view) over a string slice, so it’s kind of an adapter. Returning a &Path ties the lifetime of that borrow to the lifetime of the string slice that it’s viewing/adapting.

The owned version is PathBuf.


as the docs point out, &Path is to &str as PathBuf is to String. Path is a slice of a PathBuf, whereas Vec<T> owns it’s elements.


Thanks. This makes sense. I read the docs but missed this relationship between Path and PathBuf.