10 ms·
Rust is a bit notorious for its string-related complexity, and that's for the reasons you talked about. The most common form of string you'll see is `String`[0
by Measter 6y ago
Rust is a bit notorious for its string-related complexity, and that's for the reasons you talked about.
The most common form of string you'll see is `String`[0], or its view type `str`[1], which are UTF-8 encoded. These have most of the string functions you'd expect to have.
Of course, as you mentioned, operating systems don't all use UTF-8, which brings us to `OsString`[2], and its view type `OsStr`[3]. This is the data type that string data from the OS is represented as. Both are basically bundles of bytes, with no specific encoding. You'll note that these are in the FFI namespace.
You then have `PathBuf`[4] and its view type `Path`[5], which are wrappers around `OsString` and `OsStr` respectively, and provide path-specific functionality.
All the file system related APIs take anything that implements `AsRef<Path>`, which is runtime-cost-free for all of these types. There's not many functions that take an `OsStr`, but those that do take it in the form `AsRef<OsStr>`, which like `Path` is runtime-cost-free for all these types. None of the APIs take `PathBuf` or `OsString`.
Return values are typically `PathBuf` for file system APIs, and `OsString` for other APIs. The only exceptions I know of are the functions for getting environment variables and command line arguments, which also provide functions that return `String` because a common use case would be converting them anyway.
[0] https://doc.rust-lang.org/std/string/struct.String.html https://doc.rust-lang.org/std/string/struct.String.html
[1] https://doc.rust-lang.org/std/primitive.str.html https://doc.rust-lang.org/std/primitive.str.html
[2] https://doc.rust-lang.org/std/ffi/struct.OsString.html https://doc.rust-lang.org/std/ffi/struct.OsString.html
[3] https://doc.rust-lang.org/std/ffi/struct.OsStr.html https://doc.rust-lang.org/std/ffi/struct.OsStr.html
[4] https://doc.rust-lang.org/std/path/struct.PathBuf.html https://doc.rust-lang.org/std/path/struct.PathBuf.html
[5] https://doc.rust-lang.org/std/path/struct.Path.html https://doc.rust-lang.org/std/path/struct.Path.html