this post was submitted on 13 Aug 2024
31 points (100.0% liked)
Rust
5953 readers
14 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
For a direct replacement, you might want to consider enums, for something like
That's going to be a lot more ergonomic than shuffling trait objects around, you can do stuff like:
If you have known set of strategy that isn't extensible, enums are good. If you want the ability for third party code to add new strategies, the boxed trait object approach works. Consider also the simplest approach of just having functions like this:
Sometimes, Rust encourages not trying to be too clever, like having
get
vsget_mut
and not trying to abstract over the mutability.Thanks for the explanation! I think just using an enum will do perfectly well in my case.
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.