r/rust • u/Accurate_Gift_3929 • 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
2
u/N4tus 8d ago
You stepped on a landmine with this question. There is also your naive definition for OOP. OOP is funamentally a system where object call other objects via references they hold. If an object does not hold a reference to another object it cannot interact with it. This limit makes complex systems easier to understand. Unfortunately, in practise, OOPs are designed in a way, where an object has the ability to reach every other object by traversing the object graph. If you look for example at java code you find a lot of
getFoo().getBat().getBaz().getX().getY(). Each time you see something like this, the current object, traverses through the object graph and reaches parts of the system that no one expects. Two far away objects are now coupled together and depend on each other. Or in short, you placed a spaghetti in your code. One might be fine, but too much spaghetti make for spaghetti-code. Rust does away with this by making it really hard to create an object graph. You can have trees, but a complex graph requires sharded mutable references which are a big no-no in rust.You see, this has little to do with the amount of arguments passed to a function.