Hi, very beginner here. I'm trying a linked list implementation with enums. I've written an nth method to look up values by index:
use crate::List::*;
enum List {
Cons(i32, Box<List>),
Nil
}
impl List {
fn new() -> List {
Nil
}
fn add(self, elem: i32) -> List {
Cons(elem, Box::new(self))
}
fn nth(&self, index: u32) -> i32 {
match (index, self) {
(0, Cons(elem, _)) => *elem,
(_, Cons(_, list)) => (*list).nth(index - 1),
(_, Nil) => -999 // Throw an error
}
}
}
This works fine, but a slightly different implementation of nth does not:
fn nth(&self, index: u32) -> i32 {
match (index, *self) {
(0, Cons(elem, _)) => elem,
(_, Cons(_, list)) => (*list).nth(index - 1),
(_, Nil) => -999 // Throw an error
}
}
Here, the *self is problematic and raises this error.
error[E0507]: cannot move out of `*self` which is behind a shared reference
--> r-03-03.rs:39:23
|
39 | match (index, *self) {
| ^^^^^ move occurs because `*self` has type `List`, which does not
implement the `Copy` trait
I cannot understand these messages, especially since a method which employs match *self in a similar way does not raise this error.
fn head(&self) -> i32 {
match *self {
Cons(elem, _) => elem,
Nil => -999 // Throw an error
}
}
The above works fine.
Basically, why does match (index, *self) fail where match *self is acceptable?