Brand new Rust learner here. Can someone please explain to me what the reason for the "cannot infer an appropriate lifetime for the lifetime parameter in function call due to conflicting requirements" error is?
This is not an X-Y problem. I am sure my whole design is probably wrong and/or not idiomatic Rust. I'm learning all that eventually I hope. My question here is only about understanding this particular compiler message.
pub struct WeightedDirectedGraph<'a> {
nodes: Vec<Node<'a>>,
}
pub struct Node<'a> {
edges: Vec<Edge<'a>>,
}
pub struct Edge<'a> {
to_node: &'a Node<'a>,
cost: &'a f32,
}
impl<'a> WeightedDirectedGraph<'a> {
pub fn add_edge(&mut self, from_node_index: usize, to_node_index: usize, cost: f32) {
// get the index before adding it, since index is zero-based
let new_edge_index = self.nodes[from_node_index].edges.len();
let mut new_edge: Edge<'a> = Edge {
to_node: &self.nodes[to_node_index],
cost: &cost,
};
}
}
fn main() {}
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:19:23
|
19 | to_node: &self.nodes[to_node_index],
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime defined on the method body at 15:21...
--> src/main.rs:15:21
|
15 | pub fn add_edge(&mut self, from_node_index: usize, to_node_index: usize, cost: f32) {
| ^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:19:23
|
19 | to_node: &self.nodes[to_node_index],
| ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 14:6...
--> src/main.rs:14:6
|
14 | impl<'a> WeightedDirectedGraph<'a> {
| ^^
note: ...so that the expression is assignable
--> src/main.rs:18:38
|
18 | let mut new_edge: Edge<'a> = Edge {
| ______________________________________^
19 | | to_node: &self.nodes[to_node_index],
20 | | cost: &cost,
21 | | };
| |_________^
= note: expected `Edge<'a>`
found `Edge<'_>`