3 ms·
Then if Path is not about abstraction, why not use a raw byte slice like &[u8]
by jiwangcdi 2y ago
Then if Path is not about abstraction, why not use a raw byte slice like &[u8]
- K0nserv 2y agoThat's orthogonal. If the type was `&[u8]` instead of `Path` the type signature would be: pub fn read<P: AsRef<[u8]>>(path: P) -> Result<Vec<u8>> The reasons for it to be generic and us `AsRef` remain. The reason for Path over &[u8] is, AFAIK, because not all byte slices are valid paths on all OSs, but also because a dedicated type lets the standard library add methods such as `Path::join`
- jiwangcdi 2y agoSo abstraction is still a point, but Rust cares about memory layout as well.
- K0nserv 2y agoSort of, this API enables static dispatch, but it could also have been written as pub fn read<P: AsRef<Path>>(path: &dyn P) -> Result<Vec<u8>> In which case the size of `path` is always the same(two words[0]) and the same machine code could be used regardless of how the function is called. Rust still cares about the memory layout but because `&dyn AsRef<Path>` has the same layout for all implementations of `AsRef<Path>` there's no need for monomorphization[1]. 0: https://doc.rust-lang.org/1.80.1/reference/types/trait-object.html https://doc.rust-lang.org/1.80.1/reference/types/trait-objec... 1: https://rustc-dev-guide.rust-lang.org/backend/monomorph.html#monomorphization https://rustc-dev-guide.rust-lang.org/backend/monomorph.html...