Trouble creating business-logic and domain objects in Rust (coming from OOP languages)

44 points avwie

I am looking for some guidance in how to use Rust with writing business-logic.

Coming from OOP languages like Java, we have a lot of classes with references to each other and things like repositories etc to abstract over the creation and storage of them. I am used to fetching an object graph and are able to navigate this object graph via code.

However in Rust I immediately hit the borrow-checker, obviously. So what are some ways to have a rich domain-model and write business logic on this model in a succinct Rust way?

There are multiple routes so far I had seen:

  • Arc/Rc, and RefCell/Mutex for all the references to other objects, which is basically Rustifying the way it is done in e.g. Java references.
  • No direct links, but have them separated via some identifier (which is Copy)?

A very simple example:

I am working on some personal finance tool, so I have an Account and a Transaction struct. This Transaction struct should have a reference to the debtor and the creditor, which are both of type Account. However, they don't own the Account. I could add them to the Transaction via Rc & RefCell, but this seems needlessly complicated. I could expose it via a debtor_id/creditor_id which are some UUID. And a way to fetch and store this in a separate repository somehow.

This is a very simple object graph, but this graph can become extremely large.

Is there a general consensus on how to handle this? My preferred way would be the Copy identifiers. This forces separation. However, it is less robust.

Edit: based on the answers below I noticed that I framed the question wrong and it is now to narrowly focused on the object graph idea. Maybe to rephrase it: What is an idiomatic Rust way, or a trait oriented way, of modeling business domains and their usecases? Are there examples of projects like this?