this post was submitted on 13 Aug 2024
31 points (100.0% liked)
Rust
7902 readers
23 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 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
I spent like a week on this last month. Usually you use enumeration, but I wanted to allow client code to define their own strategies. I tried the
Box<dyn MyTrait>pattern because some of my strategies were composed of other strategies, and I wanted to clamp down on generic types. But I kept running into weirder and weirder compiler errors. Always asking for an additional restriction on the base trait. X, must beCopy, must beSend, must beSized, must be'static. On and on. My experience is if I'm getting a bunch of those then I'm off the Golden Path. So I just embraced the verbosity of using generics and its easy. Yes its more code but its better code.Some of these restrictions are reasonable, some you need to avoid. Without
dynthe compiler just figures out whether those properties are congruent, withdynyou need to choose those properties explicitly.Sendis typically reasonable and typically can be just added to the list.Sized- not sure. Idea ofdynthings typically relies on unsized things (andBoxand friends to get back to theSizedworld).'static- if you are OK at allocating here and there (i.e. not optimising for performance hard), limiting to'staticworld (i.e. without other lifetimes and inner references) can be reasonable.Syncis needed rarely, usuallySendis enough.Copybound is typically too much, unless the data is very simple. Probably you need a.clone()and/orArcsomewhere.Unpincan also be just added as needed, unless you are dealing withasyncand optimising allocations.The list of things that can be added in
...part ofdyn Trait + ...is finite, so this "on and on" won't go forever. So after some time the trait definition and main consumers are expected to stabilise.dynroad is indeed a thinner and somewhat winding road compared to main, easy way of'static + Sizedthings. But when it is really necessary (i.e. you need dynamically construct the strategies from parts, or you need to attach more strategies from plugins, or you want to avoid big bloated executables), there is little way around it.If it works without
dynthen probably it's OK to leave it that way.Each of those
dyn,async,impl<'a>,Pin,unsafe,macro_rules!things bump Rust experience a step right onEasy-Normal-Hard-Nightmarescale.