• 0 Posts
  • 2 Comments
Joined 1 year ago
cake
Cake day: June 26th, 2023

help-circle
  • 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.