4 ms·
Rust's model is similar to a cleaned-up and guaranteed safe use of modern C++ smart pointers and references. A few of the improvements that Rust offers are com
by lambda 11y ago
Rust's model is similar to a cleaned-up and guaranteed safe use of modern C++ smart pointers and references.
A few of the improvements that Rust offers are compiler enforced move semantics by default, so assigning, returning, or passing a Box<T> (similar to unique_ptr<T> in C++) will move the ownership to the new location and statically check that you never try to access the old location. In C++, you have to explicitly call std::move(), and checks to make sure you don't reference the old one happen at runtime.
Rust also does safer checking of use of references. In C++, it's possible to return a reference to a stack variable which is no longer valid. In Rust, the lifetimes of references are tracked statically, so you can never have a dangling reference.
So, while the RAII pattern, use of smart pointers, and use of references, will feel fairly familiar to someone familiar with modern C++, they are actually generally more convenient and more safe in Rust.
Rust does not have classes. You define plain old data structures, and use traits to provide polymorphic behavior. Traits are somewhat like interfaces which can contain default implementations of methods. Traits can be used to constrain types. Traits can be used to provide either static (compile time) dispatch, or runtime dispatch, depending on whether the object is monomorphized at compile time or accessed through a fat pointer that includes a vtable to dispatch at runtime.
Rust provides generics which fill a similar niche to templates in C++. In some ways, they are more powerful as arguments can be constrained by traits; in some ways they are less powerful than C++ templates.
For an introduction to traits in Rust, take a look at the book: https://doc.rust-lang.org/book/traits.html https://doc.rust-lang.org/book/traits.html
Rust doesn't provide operator overloading directly, but use of operators is equivalent to just calling a method defined on a particular trait in Rust. So, "a + b" is will work for any types that implement the Add trait (https://doc.rust-lang.org/std/ops/trait.Add.html https://doc.rust-lang.org/std/ops/trait.Add.html), and is equivalent to calling a.add(b).
- ant6n 11y agoOne thing I'd miss from C++ are the alternative operator representations for && and ||, and and or.