Hi, guys.
I'm doing course on algorithms, and to make it more interesting, I'm implementing algorithms in rust.
Currently I'm trying to create Graph.
pub struct Graph<'l, T: 'l> {
pub verticies: Vec<Vertex<'l, T>>,
pub edges: Vec<Edge<'l, T>>
}
pub struct Vertex<'l, T: 'l> {
pub payload: &'l T
}
pub struct Edge<'l, T: 'l> {
pub tail: &'l Vertex<'l, T>,
pub head: &'l Vertex<'l, T>
}
In my view, Graph should own it's verticies
and edges
. In contrast, edges should only have reference to it's edges.
The problem arrives when I try to create Graph:
let lb = Vertex{payload: &"left bottom".to_string()};
let rb = Vertex{payload: &"right bottom".to_string()};
let lt = Vertex{payload: &"left top".to_string()};
let rt = Vertex{payload: &"right top".to_string()};
let top = Edge {tail: <, head: &rt};
let bottom = Edge {tail: &lb, head: &rb};
let left = Edge {tail: <, head: &lb};
let right = Edge {tail: &rt, head: &rb};
let diagonal = Edge {tail: &lb, head: &rt};
let graph = Graph {
verticies: vec![lb, rb, lt, rt],
edges: vec![top, bottom, left, right, diagonal]
};
When I obtain reference to vertex
by doing let top = Edge {tail: <, head: &rt};
, both verticies
freeze, so it becomes impossible to use them later when I create Graph
.
How can I solve this? Maybe I use the wrong approach to create data structure in rust?