Conversation

Replying to
I think I should learn it to get a feel for this way of thinking. I tend to use the stack a lot and values and const ref, when I really need custom heap allocations I do that with unique_ptr. This seems very “shared heap memory oriented” 🤔 I try to share as little as possible…
2
Replying to
Rust encourages heavily uses the stack and you're pushed towards designing around unique ownership more than C++. You use lightweight references a lot more aggressively though, particularly with arrays/strings. Shared ownership + mutability is very restricted and kinda painful.
2
2
Replying to
It's basically just the same thing but with moves as the default and references everywhere. So, for example, if you're splitting a string in Rust, the natural way to do that is an iterator (reference) of string slices (more references) and then taking more slices of those, etc.
1
2
So, for example, it's really natural to do complex parsing with multiple layers without allocating any new strings but rather taking views into views into views. It's not something weird but rather the most natural and easiest approach. If you want to allocate, that's explicit.
1
2
It's more like C than C++ in terms of copying and allocation. Assigning, passing parameters and returning is always a shallow copy like C. If the type has a destructor, that's a move of ownership. There is no move constructor concept, etc. though and it just works like C values.
1
2
References are also more like C pointers (but safe and non-null) than C++ references. They're simply regular values / types. &[T] and &str (slices) are also just a case of &T. Box<[T]> (rarely used) can be converted to/from Vec<T> (converting from it drops excess capacity first).
1
2
Most functions working with strings use them via &str, and similar with arrays. Rust's String is like std::string and Vec<T> is like std::vector<T>. They are far more interoperable with each other, references and smart pointers though.
1
2
So, for example, you can go from Box<[u8]> or Vec<[u8]> to String without allocation. It just has to check that it's valid UTF-8 and can make it a String. You usually write code via references because it's simpler and reusable. Similarly, slices, not references to String, etc.
1
2
An API to parse a number from a string will naturally take a &str parameter. So, it's natural to be passing in a view to that. It doesn't care if the &str points into a String, a string constant (&str with static lifetime) or where it came from (multiple layers of slicing, etc.).
1
2
Closures and trait objects fit into the same system. You usually use traits (type classes / interfaces) as bounds on the generics (you have to declare all requirements in the signature, unlike C++ templates) but you can also use those as objects. It works like [T] and str.
1
2
Show replies