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 thread.
View all comments
2 points

Minor nit: Kotlin is decidedly not a functional language.

Design patterns in OOP exist purely to solve the problems created by OOP itself. If you have a language with proper ADTs and higher order functions, the need for traditional design patterns disappear since the problems they solve are first-class features baked into the language.

The first-class replacement for the Strategy pattern (and many other patterns such as the Visitor pattern) is sum types (called enums in Rust).

permalink
report
reply
3 points

Truth has been spoken.

Except that Kotlin is functional (just like Rust, C++, Visual Basic, JavaScript,…). It is, however, not Pure Functional (like Haskell or Lean4 would be - if you haven’t checked out Lean4, I can recommend it, great fun).

(Sauce: https://en.wikipedia.org/wiki/List_of_programming_languages_by_type#Functional_languages)

permalink
report
parent
reply
4 points

That list also counts Java and C# as “functional languages”. I wouldn’t take it too seriously. Ocaml, Scala, F#, etc. are impure functional languages. Kotlin absolutely is not. Having a couple of features you might find in functional languages does not make a language functional. Kotlin is still very much an OOP-based language. It’s basically a somewhat nicer Java.

permalink
report
parent
reply
3 points

I know, from a mathematics standpoint it does not make sense, but from how the term is used nowadays in programming it does: Those languages allow to compose functions, pass functions as parameters, return functions, etc.

permalink
report
parent
reply

Rust

!rust@programming.dev

Create post

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

Wormhole

!performance@programming.dev

Credits
  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

Community stats

  • 610

    Monthly active users

  • 244

    Posts

  • 826

    Comments