Dear all,
I'm really stuck with this problem. I try to create some basic algorithm implementation in rust, just for learning. I'm coming from lanugages like javascript, python and go.
I like to create a bin tree insert alg.
struct Node<'a> {
val: isize,
left: &'a Option<Box<Node<'a>>>,
right: &'a Option<Box<Node<'a>>>,
}
impl Node<'_> {
fn new<'a>(val: isize) > Node<'a> {
Node {
val,
left: &None,
right: &None,
}
}
}
struct BinTree<'a> {
root: Option<Box<Node<'a>>>,
}
impl BinTree<'_> {
fn insert(&mut self, z: isize) {
let z_node = Some(Box::new(Node::new(z)));
let mut x = &self.root;
let mut y;
loop {
y = x;
x = match x {
Some(n) => {
if z < n.val {
&n.left
} else {
&n.right
}
}
None => {
break;
}
}
}
if let Some(n) = y {
if z < n.val {
n.left = &z_node;
} else {
n.right = &z_node;
}
} else {
self.root = z_node;
}
}
}
The error output:
error[E0594]: cannot assign to `n.left` which is behind a `&` reference
> src/binstree.rs:45:17

45  n.left = &z_node;
 ^^^^^^^^^^^^^^^^ `n` is a `&` reference, so the data it refers to cannot be written
error[E0594]: cannot assign to `n.right` which is behind a `&` reference
> src/binstree.rs:47:17

47  n.right = &z_node;
 ^^^^^^^^^^^^^^^^^ `n` is a `&` reference, so the data it refers to cannot be written
I read about the references in rust. But i completelly los about it. I tought y is going to be a reference to a option > box > node and i can mutate. But this error for me means nothing Pls im struggle with this like hours.
Thanks