I have a problem with lifetimes/borrowing with my Graph
object.
fn main() {
let mut g = Graph {
nodePointer: &mut 0,
edgePoi
Consider this :
struct Foo<'a> {
x: &'a i32,
}
As the book states:
So why do we need a lifetime here? We need to ensure that any reference to a Foo cannot outlive the reference to an i32 it contains.
If you write something like:
impl<'a> Graph<'a> {
pub fn add_node(&'a mut self, data: (u64, u64)) -> usize {
...
the lifetime declaration &'a mut self
is not for the purpose of relating the lifetime of Graph
instance with the contained references,
but for declaring that for mutable self
references hold the same lifetime 'a
declared for Graph
field references:
fn main() {
let mut g = Graph { // <------------
nodePointer: &mut 0, // |
edgePointer: &mut 0, // lifetime |
nodes: &mut Vec::new(), // of Graph | 'a
edges: &mut Vec::new(), // references |
}; // |
let node1 = Graph::add_node(&mut g, (1, 1)); // |
let node2 = Graph::get_node(&mut g, 0); // |
} //<-------------
Where g.get_node(0)
has been rewritten as Graph::get_node(&mut g, 0)
just for explicitly exposing the &mut
reference
Looking at the lifetime of 'a
it is clear that the reference &mut g
is borrowed mutably more than once, and this causes the error.