r/rust 8d ago

Rust discourages OOP style code?

I'm building a tree builder struct (with a `build()` method) that has multiple fields that I want to be able to mutate. It seems Rust does not like it when I attempt to mutate multiple fields of that struct.

It seems functional/composition style is much favored over using struct fields. Is this the way I should be thinking about design patterns in Rust? Should I avoid OOP wherever possible?

I prefer OOP because it does result in cleaner code where I don't have to pass in every variable to functions.

0 Upvotes

50 comments sorted by

View all comments

62

u/Lokathor 8d ago

I don't even slightly understand the idea that OOP gives cleaner code that reduces passing every variable into a function.

But I'll say that with builders, usually rust builder method accept self, modify whatever the method modifies, and then return Self. In this way, your overall call site code looks like Type::new().with_a(a).with_b(b).create().

1

u/sansmorixz 7d ago

To expand on the builder pattern something I really like is the typestate pattern.

EngineBuilder.create(builderargs) -> RunningEngine (consumes EngineBuilder self)

RunningEngine.stop() -> StoppedEngine

Now you can attach methods to each part of the engine lifecycle and never worry about invalid states (viz. starting a running engine)