Hi,
I've read all sorts of tutorials and documentation many times and I thought I understood how ownership and borrows work, but now I've run into this problem (this is a simplified form of the code to represent the problem):
struct Node {
value: i32
}
struct Edge<'a> {
from: &'a Node,
to: &'a Node
}
struct Tree<'a> {
nodes: Vec<Node>,
edges: Vec<Edge<'a>>
}
fn find_node<'a>(tree: &'a Tree, value: i32) -> Result<&'a Node, String> {
for i in 0..tree.nodes.len() {
if tree.nodes[i].value == value {
return Ok(&tree.nodes[i])
}
}
return Err("ups".to_string())
}
fn add_if_missing<'a>(tree: &'a mut Tree, value: i32) -> Result<&'a Node, String> {
match find_node(&tree, value) {
Ok(node) => Ok(node),
Err(_) => {
let n_ele = Node { value: value };
tree.nodes.push(n_ele);
Ok(&tree.nodes[tree.nodes.len()])
}
}
}
fn main() {
let mut tree = Tree { nodes: vec![], edges: vec![] };
let node = add_if_missing(&mut tree, 4);
}
I don't understand why the compiler states that "returns a value referencing data owned by the current function". After all, line 25 should return a reference to an array element. It is not a value whose lifetime will end with the end of the function.
Just as I don't understand why I can't do the mutable borrow in line 28, after all the immutable borrow from line 24 has already completed.
How should I write this type of operation in Rust?
Where can I read to better understand how it works? As you can see, simple examples of type
let y = &a;
fun(a)
are insufficient for me.