New rustacean here. I'm trying to implement a directed graph data structure but I can't find a way to satisfy borrow checker.
I spent a decent amount of time on The Rust Programming Language  Lifetimes and I try to understand compiler hints without any success.
Relevant code:
#[derive(Debug, PartialEq, Eq)]
struct Vertex {
name: String
}
#[derive(Debug, PartialEq, Eq)]
struct Edge<'a> {
weight: u32,
from: &'a Vertex,
to: &'a Vertex
}
#[derive(Debug, PartialEq, Eq)]
struct Graph<'a> {
vertices: Vec<Vertex>,
edges: Vec<Edge<'a>>,
}
impl <'a> Graph<'a> {
fn new() > Graph<'a> {
Graph {
vertices: Vec::new(),
edges: Vec::new(),
}
}
fn add_vertex(&mut self, name: String) {
self.vertices.push(Vertex{name});
}
fn get_vertex(&self, name: &str) > Option<&Vertex> {
self.vertices.iter().find(x x.name == name)
}
fn add_edge(&mut self, weight: u32, v1: &str, v2: &str) {
let v1 = self.get_vertex(v1).unwrap();
let v2 = self.get_vertex(v2).unwrap();
self.edges.push(Edge{
weight,
from: &v1,
to: &v2
});
}
fn get_edges(&self, name: &str) > Vec<&Edge> {
let v = self.get_vertex(name).unwrap();
self.edges.iter().filter(edge edge.from == v).collect()
}
}
Compiler error:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
> 2015/day09/src/lib.rs:49:23

49  let v1 = self.get_vertex(v1).unwrap();
 ^^^^^^^^^^

note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 48:5...
> 2015/day09/src/lib.rs:48:5

48  / fn add_edge(&mut self, weight: u32, v1: &str, v2: &str) {
49   let v1 = self.get_vertex(v1).unwrap();
50   let v2 = self.get_vertex(v2).unwrap();
51   self.edges.push(Edge{
... 
55   });
56   }
 _____^
note: ...so that reference does not outlive borrowed content
> src/lib.rs:49:18

49  let v1 = self.get_vertex(v1).unwrap();
 ^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 32:7...
> src/lib.rs:32:7

32  impl <'a> Graph<'a> {
 ^^
note: ...so that the expression is assignable
> 2015/day09/src/lib.rs:51:25

51  self.edges.push(Edge{
 _________________________^
52   weight,
53   from: &v1,
54   to: &v2
55   });
 _________^
= note: expected `Edge<'a>`
found `Edge<'_>`
error: aborting due to previous error
For more information about this error, try `rustc explain E0495`.
I read rustc hint (rustc explain E0495
) but couldn't transpose it to my case.
Can you explain me what is the problem in other words and help me satisfy the borrow checker pls ?
Thanks