this post was submitted on 13 Aug 2024
31 points (100.0% liked)

Rust

5999 readers
21 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

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
31
Strategy Pattern in Rust (programming.dev)
submitted 3 months ago* (last edited 3 months ago) by [email protected] to c/[email protected]
 

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!

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 9 points 3 months ago (4 children)

For a direct replacement, you might want to consider enums, for something like

enum Strategy {
    Foo,
    Bar,
}

That's going to be a lot more ergonomic than shuffling trait objects around, you can do stuff like:

fn execute(strategy: Strategy) {
    match strategy {
        Strategy::Foo => { ... }
        Strategy::Bar => { ... }
}

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:

fn execute_foo() { ... }
fn execute_bar() { ... }

Sometimes, Rust encourages not trying to be too clever, like having get vs get_mut and not trying to abstract over the mutability.

[–] [email protected] 2 points 3 months ago (3 children)

Thanks for the explanation! I think just using an enum will do perfectly well in my case.

[–] [email protected] 2 points 3 months ago (1 children)

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,

  • methods use dynamic dispatch in this case
  • requires heap allocation

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.

[–] [email protected] 3 points 3 months ago (1 children)

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.

[–] [email protected] 4 points 3 months ago

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.

load more comments (1 replies)
load more comments (1 replies)