How to make a child structure reference a member of its parent?


#1

In this project I’m working on I have one struct that holds several other smaller structs. All the child structs need a reference to the one common resource. I was thinking the best way to do this is to make this shared resource a member of the parent struct and pass a reference to all the children, but now I don’t know exactly how to do this rust. I’ve written a smaller example gist to show what I’m thinking. https://gist.github.com/stusmall/786539a8bcfe6a0035616eca3d1ced47

In the example Outside is the parent struct, ToRef is what I want to be the shared resource and Inside is the child. What I really want to do is hand a reference to Outside::b to inside but I don’t know if that’s possible. Any tips?


#2

Also I know I can use Arc to share this, but that doesn’t seem like it should be necessary.


#3

I think you may find this SO answer useful: http://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct.


#4

FWIW, the rental crate allows one to create a structure which stores both the owned value and a reference to it: https://github.com/jpernst/rental.


#5

I appreciate the update on this! Whats funny is this exact topic came up again today.