Hi!
I'm trying to write a program to draw objects (e.g. rectangle, triangle, etc.) on screen.
The problem I have is accessing dependent information between objects. For example, I want to keep position data separate from the frame of reference (i.e. position of object A is relative to object B).
pub struct Rectangle{
position: Point, // x, y relative position
origin: Option<Point>, // Some other object's position
// Some other properties
}
If the parent
or origin
moves, the said object will move with it, while keeping it's position data constant.
What would be an appropriate way to model this in Rust? I am currently using Rc<RefCell<Point>>
as position and having Weak<RefCell<Point>>
as origin to track another object's position.
pub struct Rectangle{
position: Rc<RefCell<Point>>, // x, y relative position
origin: Weak<RefCell<Point>>, // Some other object's position
// Some other properties
}
In terms of ergonomics, this works okay for me after grouping position & origin into it's own struct, and defining type alias and trait methods to operate on it. However, if the level of dependency or interaction grows (e.g. keeping reference to entire parent object), I think this approach can get challenging.
I looked into using arena type approach, in which I will only keep the index of parent object. However, I struggle to access parent object from arena while having mutable borrow of current object. Am I misunderstanding how arena (e.g. generational-arena) is supposed to be used?
Modelling inter-object relationship and dependency has been quite challenging for me in Rust, so I would really like to figure this out.
Thank you for any help in advance!