Hey there, I’m currently learning Rust (coming from object-oriented and also to some degree functional languages like Kotlin) and have some trouble how to design my software in a Rust-like way. I’m hoping someone could help me out with an explanation here :-)

I just started reading the book in order to get an overview of the language as well.

In OOP languages, I frequently use design patterns such as the Strategy pattern to model interchangeable pieces of logic.

How do I model this in Rust?

My current approach would be to define a trait and write different implementations of it. I would then pass around a boxed trait object (Box<dyn MyTrait>). I often find myself trying to combine this with some poor man’s manual dependency injection.

This approach feels very object oriented and not native to the language. Would this be the recommended way of doing things or is there a better approach to take in Rust?

Thanks in advance!

  • _Vi
    link
    fedilink
    arrow-up
    4
    ·
    4 months ago

    Always asking for an additional restriction on the base trait.

    Some of these restrictions are reasonable, some you need to avoid. Without dyn the compiler just figures out whether those properties are congruent, with dyn you need to choose those properties explicitly.

    must be Copy, must be Send, must be Sized, must be 'static

    • Send is typically reasonable and typically can be just added to the list.
    • Sized - not sure. Idea of dyn things typically relies on unsized things (and Box and friends to get back to the Sized world).
    • 'static - if you are OK at allocating here and there (i.e. not optimising for performance hard), limiting to 'static world (i.e. without other lifetimes and inner references) can be reasonable.
    • Sync is needed rarely, usually Send is enough.
    • Copy bound is typically too much, unless the data is very simple. Probably you need a .clone() and/or Arc somewhere.
    • Unpin can also be just added as needed, unless you are dealing with async and optimising allocations.

    On and on.

    The list of things that can be added in ... part of dyn 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.

    I’m off the Golden Path

    dyn road is indeed a thinner and somewhat winding road compared to main, easy way of 'static + Sized things. 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.

    So I just embraced the verbosity of using generics and its easy. Yes its more code but its better code.

    If it works without dyn then 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 on Easy-Normal-Hard-Nightmare scale.