Start United States USA — software My Second Cup of Rust

My Second Cup of Rust

164
0
TEILEN

Last week, I drank my first cup of Rust. I learned concepts that are foreign in the languages I know. This week I want to drink the second cup and see where …
Join the DZone community and get the full member experience. Last week, I drank my first cup of Rust. I learned concepts that are foreign in the languages I know: ownership, borrowing, and lifetimes. This week I want to drink the second cup and see where it leads me. It’s time to implement another exercise from the initial exam: We need to change the model to add a sidekick attribute of type Super. The implementation seems easy enough. Unfortunately, the above code doesn’t compile: It seems that in Rust, a type cannot reference itself. Let’s follow the compiler’s suggestion. An „easy“ fix is to use a reference instead of a type. While the type compiles, the tests don’t: Back to square one. The compiler also hinted at using Box. All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box. A box is a smart pointer to a heap allocated value of type T. When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed. Rust By Example — Box, stack and heap Here’s the new code that uses Box: With it, everything compiles, including the test samples! Finally, the solution is straightforward: Testing the solution doesn’t bring new insights into the language.

Continue reading...