Basically what I tried to achieve is the following graph-kinda structure in C.
#include <stdlib.h>
struct node{
struct node *next;
};
int main() {
struct node* n = malloc(sizeof(struct node));
n->next = n;
return 0;
}
what I have tried in Rust:
struct Node {
next: Vec<Rc<RefCell<Node>>>,
}
fn main() {
let n = Rc::new(RefCell::new(Box::new(Node { next: vec![] })));
n.borrow_mut().next = vec![n.clone()];
}
and it works but it uses a Vec
. What I really want:
struct Node {
next: Rc<RefCell<Node>>,
}
fn main() {
let n = Rc::new(RefCell::new(Box::new(Node { next: ? })));
n.borrow_mut().next = n.clone();
}
I cannot even construct a Node in this circumstance. One solution is to use Option, then I can initialize with None, but it adds a burden (Imagine we want a cyclic chain for example).
Link I have read: https://github.com/nrc/r4cppp/blob/master/graphs/src/rc_graph.rs https://rust-leipzig.github.io/architecture/2016/12/20/idiomatic-trees-in-rust/
Is the solution they called arena the 'rustic' way of solving the problem?
I believe RefCell
has a runtime cost, is this statement true?