I have a problem with lifetimes/borrowing with my Graph
object.
fn main() {
let mut g = Graph {
nodePointer: &mut 0,
edgePoi
Your problem arises from a misuse of lifetimes, specifically in your signature of add_node
:
pub fn add_node(&'a mut self, data: (u64, u64)) -> usize
In this signature, you are stating that add_node
takes an &'a mut self
on a Graph<'a>
; in other words, you are telling Rust that this method needs to take a mutable borrow on the graph that can't be dropped before the end of the Graph's lifetime, 'a
. But since it's the graph itself holding a reference to the graph, the only time that reference will be dropped is when the graph itself is dropped.
Since add_node
doesn't require you to return a reference to any object within the struct, holding onto that borrow is irrelevant. If you alter your add_node
method to remove the explicit lifetime:
pub fn add_node(&mut self, data: (u64, u64)) -> usize
then your example no longer raises an error, because add_node
is now only borrowing self
until it's finished with the function. (Under the hood, this effectively creates a second lifetime 'b
and makes the signature into &'b mut self
)
See the playground for proof.