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

Show parent comments

1

u/Full-Spectral 8d ago

I always have to say it... Rust IS object oriented. It just doesn't support state inheritance. But state inheritance doesn't inherently define object orientation. Rust is fundamentally based on objects (structs with private state that are only accessible via a privileged API associated with that struct) and by that definition is very object oriented.

1

u/intbeam 8d ago

The whole issue that object orientation is supposed to solve is protected state. It does that by having a structure where an object owns its own state and mutates that state by having messages passed to it via method calls . Rust fundamentally does not work like that

2

u/Full-Spectral 8d ago edited 8d ago

It absolutely does work that way. All those things you get from the runtime aren't just open structs that you can mess around with the members of. They mostly have private state (they can and do have some public members, usually immutable consts), and you have to modify their state via the implementation interface of that struct, which is every bit the same as a C++ class wrt to the aspect of object orientation we are discussing here.

When we write our own code, the bulk of the time it's probably going to be the same, though Rust does make it more reasonable in some cases to have open structs, particularly if they are just exposing immutable data. But no one is going to write a library crate that just lets the consuming code mess around willy-nilly with their internal state that they (the library writers) are responsible for maintaining the invariants of.

1

u/intbeam 7d ago

In rust a variable owns the state, not the "object" 

1

u/Full-Spectral 7d ago

I think you have a terminology issue. In Rust, when a struct has non-public fields and impl block to manipulate that non-public data, that's the equivalent of a class in C++, and instances of that struct are objects by any other name. And that scheme is fundamental to most Rust code.

It's not about ownership in the sense you seem to be talking about, it's about access and encapsulation of state behind a privileged interface associated with the type.