[SOLVED] 1 Sender, 1 Receiver, 1 Element, 1 Thread



tldr: I need a data structure that can hold one element, can be written from one place and later can be read from another place, all within the same thread.

I have have a graph of structs to do calculations. Each struct uses the results of its predecessors for its own calculation. The successors then in turn use those results for their calculations. My setting is NOT multi-threaded! One thread does all the calculations in a precalculated order, s.t. there are no synchronization issues.

Call it a “call graph” if you will, analogously to the usual call stack.

What I need is a data structure that can be written from one struct and later read from another struct. Every result is written exactly once and later read exactly once. In other languages, I’d just give the producer a member field to write its result to and the consumer would have a pointer to that field to read the result later. But the borrow checker forbids that. An mpsc queue for each edge of the graph would solve the problem, but this is definitely a huge overkill. Can you recommend anything to solve this problem, preferably from the standard library?

Thanks in advance for your ideas and thanks for reading :slight_smile:


A Cell or RefCell, depending on the value type, seems appropriate.


Thank you very much. This indeed solves my problem. I completely forgot about those types. My Rust seems to be a little rusty.


It happens :slight_smile:

Another thought is perhaps wrapping an Option<YourData in the cell and then changing the option to None when you consume the output; you set it to Some when producing the data. That might help you enforce (at runtime albeit) the “produce once, consume once” protocol you have.