3 ms·
What if you want to add a reference field to a struct? That's the point where I usually get pretty upset with how Rust works.
by teaearlgraycold 2y ago
What if you want to add a reference field to a struct? That's the point where I usually get pretty upset with how Rust works.
- MrJohz 2y agoYou probably don't want a reference field in a struct, at least to begin with. It's a lot easier to reason about structs if they contain owned data only, and you take a reference to the entire struct. There are some specific cases where it might be sensible, or even necessary to do that, but for someone who is still learning lifetimes, these cases are unlikely to come up. I recommend reading Steve Klabnik's "When should I use String vs &Str?" post, which is generally good advice when deciding between owned data and references. The "Level 4" section covers the case of references in structs.
- duped 2y agoYou get a lot more compiler help than when you try and put a reference in a class in C++, and if you want to use smart pointers its even better because you'll never have to learn about move and copy constructors or copy and move assignment operators.
- deleted 2y ago[deleted]