Create two structs that contain reference to each other

I am trying to migrate my Go project to Rust. Part of the code involves a struct called Transmitter which get messages from other sources and then hand them to another struct called MsgCore, which then processes these messages for further action. A Transmitter instance is bound with a MsgCore by containing each other's reference. You can see a simplified version in Go Playground.

However, I'm aware that it is hard to implement this in Rust since:

  1. In Rust, all fields in a struct must be initialized together with the struct.
  2. The limitations of lifetime and ownership.

I wonder if there are some ways to do similar things in Rust, or simply bypass the limitations via a better implementation. I have referred to this post, but it did not answer my question well.

I'm not an experienced Rust developer. Any help would be appreciated.

It sounds like you want an actor? You can read about those here: Actors with Tokio – Alice Ryhl

1 Like

I've come up with a solution that, instead of binding MsgCore to Transmitter in reverse, Transmitter passes the reference to itself to MsgCore when reporting the message. You can find the code here in Rust Playground.

It may not be optimal and is not exactly I wish to have, so I'm still open to any suggestions.

These type of references in Rust can't use temporary loans (&). It's typically done using Arc. Wrap your MsgCore in Arc<MsgCore>, and then you will be able to reference it from each transmitter as a clone of Arc. If you also need multiple shared references to Transmitter - make it Arc<Transmitter>.

When using Arc, the objects become read-only by default. To mutate them you will need "interior mutability", e.g. Arc<Mutex<Transmitter>>. Alternatively you can use Mutex on individual fields, or use AtomicUsize for integers.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.