4 ms·
Where are you seeing four string types? As far as I know, there's only `String` and `str`. Heap allocated vs. stack/statically allocated. There's also things li
by neurotrace 9y ago
Where are you seeing four string types? As far as I know, there's only `String` and `str`. Heap allocated vs. stack/statically allocated. There's also things like `CString` and `OsString` but I don't think I've had to deal with those. If so, it was so similar to working with any other string that I didn't even notice.
I'm still relatively new to Rust but this is my understanding. Please correct me if I'm wrong.
- Rusky 9y ago> Heap allocated vs. stack/statically allocated. `str` is very rarely stack allocated, and often points into a heap-allocated `String`. Further, there's an optimization on the table that will let `String`s point to static allocations. The distinction is rather owned vs borrowed. A `String` is in charge of the memory it uses, so it can grow it by reallocation, free it when it goes out of scope, etc. A `str` is not in charge of the memory it uses- it's only a pointer into some memory that something else owns, whether that's a static allocation or a `String` or some other data structure.
- neurotrace 9y agoAhhh, that makes a lot of sense. Thanks for the correction.
- eeereerews 9y agoA `str` is just an unsized blob of UTF-8 data. It's `&str` that is the (fat) pointer.
- Rusky 9y agoYou're right; I kind of left that out since it's not (currently) possible to have a bare `str` anyway and there are more ways to work with one than just `&str` (`Cow<str>`, `Box<str>`, `Rc<str>`, etc).
- kibwen 9y agoThere are two string types in Rust: String and &str. The CString and OsString types only exist for FFI and platform-dependent interop (because unlike Rust's string types, there's no guarantee that the rest of the world is UTF8-encoded). The only time you'd use CString and OsString (or see them get used) is at the very edges of your system, and you'd convert them into String or &str as soon as possible (or Vec<u8>, but that's hardly a "string type").