this post was submitted on 13 Aug 2024
31 points (100.0% liked)
Rust
6009 readers
7 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
To expand on why generics are preferred, just in case you haven't seen these points yet: the performance downsides of
Box<dyn MyTrait>
are,There is also a possible type theory objection which is that normally there is a distinction between types and traits. Traits are not types themselves, but instead define sets of types with shared behavior. (That's why the same feature in Haskell is called a "type class", because it defines a class of types that have something in common.) But
dyn
turns a trait into a type which undermines the type/trait distinction. It's useful enough to justify being in the language, but a little unsettling from a certain perspective.That makes sense, thanks again! I think dynamic dispatch is not as much of a performance issue in my case, yet you're totally right not to waste resources that aren't actually needed. Keeping things on the stack if possible is also a good thing.
I'll definitely need to read more about Rusts type system but your explanation was already very helpful! I think this might be why my initial approach felt unnatural - it works but is quite cumbersome and with generics there seems to be a more elegant approach.
Yeah the performance differences don't matter in most cases. Rust makes it tempting to optimize everything because the language is explicit about runtime representations. But that doesn't mean that optimizing is the best use of your time.