I'm creating a list-like structure with an enum:
#[derive(Debug, PartialEq, Eq)]
enum Cons<T: Clone> {
Cons(T, Box<Cons<T>>),
Null
}
However, I'm having trouble making a map method for this:
pub fn map<F,S>(&self, fun: F) -> Cons<S>
where F: Fn(T) -> S, S: Clone
{
match self {
&Cons::Null => Cons::Null,
&Cons::Cons(ref head, ref tail) => Cons::new(fun(*head), tail.map(fun)),
}
}
I'll get this:
error[E0507]: cannot move out of `*head` which is behind a shared reference
--> src/lib.rs:50:56
|
50 | &Cons::Cons(ref head, ref tail) => Cons::new(fun(*head), tail.map(fun)),
| ^^^^^ move occurs because `*head` has type `T`, which does not implement the `Copy` trait
After some attempts mixing and matching referencing and dereferencing, I gave up and used clone:
&Cons::Cons(ref head, ref tail) => Cons::new(fun(head.clone()), tail.map(fun)),
While it works, I'm not quite sure why the value has moved. I read the chapter on references and borrowing in the Rust book, but I didn't find anything there. Also, I have read about the ref keyword, but it just seems like the same thing as &, but in destructuring. I even looked at Rust by example for moves and I still don't understand where my head has gone to. So uh, can you help me find where my head went?
I do understand what borrowing/moves is/are, I just don't understand why it has happened here.