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!

  • 2xsaiko@discuss.tchncs.de
    link
    fedilink
    arrow-up
    11
    ·
    3 months ago

    Traits like std::io::Write are essentially Strategy pattern. Take a look at how that’s used. You’re doing it mostly how I would, except for the Box<dyn T>. Generally it’s preferred to use generic functions/types in Rust instead of dynamic dispatch, i.e. have a fn do_something<T: MyTrait>(imp: T) instead of a fn do_something(imp: &dyn MyTrait).

    • abrahambelch@programming.devOP
      link
      fedilink
      arrow-up
      6
      ·
      3 months ago

      Thanks for the advice! I didn’t know generic functions were preferred. But it makes perfect sense if you think about it.