-2

I am learning Rust from a C++/Java background, and I have the following pattern

struct Node<'a> {
    network_manager: NetworkManager<'a>,
}

struct NetworkManager<'a> {
    base_node: &'a Node<'a>,
}

The node contains the threadpool that the NetworkManager uses to "handoff" messages once they've been processed. Because of the recursive call, it is not possible to set the base_node field in the NetworkManager immediately. In Java, I would leave it as null and have a second method that is called after the constructor called initialise(BaseNode node) that would set the base_node field (ensuring that there are no calls to the network manager before initialise is called).

What is the idiomatic way of doing this in Rust? The only way I can think of is to make base_node an Option type, but this seems suboptimal.

In general, what is the "right" way in Rust to deal with situations where A points to B and B points to A, and where (as in my case), refactoring is not possible?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1018513
  • 1,682
  • 1
  • 20
  • 42
  • 1
    Another nitpick: "make base_node an Option type, but this seems suboptimal" but that's what you were doing in Java and you though that was fine. – mcarton Dec 13 '19 at 12:01
  • @mcarton: That will not work since there can only be one owner of a node - either the local variable accessing it or the network manager. Backpointers need more complex references, e.g. `Rc>`. – CoronA Dec 13 '19 at 12:04
  • I know, but he was still not making a fair comparison. – mcarton Dec 13 '19 at 12:05
  • 1
    *refactoring is not possible* Uh, why not? You haven't shown any code that actually uses these types. What is *the recursive call*? There is no recursion here. – trent Dec 13 '19 at 12:11

1 Answers1

1

From my experience, these situations are very different from other languages. In "safe, simple, everyday Rust" having backpointers/pointers within the struct is complex since it leads to non-trivial problems. (Consider what would happen if you would move Node around in memory: How would you properly update the backpointer in NetworkManager?)

What I usually resort to is simply passing base_node as a parameter to the functions that need the backpointer. This is sometimes easier said than done, but leads to code that clearly states ownership.

phimuemue
  • 34,669
  • 9
  • 84
  • 115