I followed the approach mentioned in https://ricardomartins.cc/2016/06/08/interior-mutability for creating a graph in Rust using Rc
and RefCell
.
type NodeRef<i32> = Rc<RefCell<_Node<i32>>>;
#[derive(Clone)]
// The private representation of a node.
struct _Node<i32> {
inner_value: i32,
adjacent: Vec<NodeRef<i32>>,
}
#[derive(Clone)]
// The public representation of a node, with some syntactic sugar.
struct Node<i32>(NodeRef<i32>);
impl<i32> Node<i32> {
// Creates a new node with no edges.
fn new(inner: i32) -> Node<i32> {
let node = _Node { inner_value: inner, adjacent: vec![] };
Node(Rc::new(RefCell::new(node)))
}
// Adds a directed edge from this node to other node.
fn add_adjacent(&self, other: &Node<i32>) {
(self.0.borrow_mut()).adjacent.push(other.0.clone());
}
}
#[derive(Clone)]
struct Graph<i32> {
nodes: Vec<Node<i32>>,
}
impl<i32> Graph<i32> {
fn with_nodes(nodes: Vec<Node<i32>>) -> Self {
Graph { nodes: nodes }
}
}
I think this approach will lead to memory leaks in case of cyclic graphs. How can I fix that?