In trying to recall what I learnt last night from the third chapter of Rust By Example I've created an enum
linked-list type this way:
#[derive(Debug)]
enum List {
Nil,
Cons(i32, Box<List>),
}
I've attempted attaching a tail()
method to this type as follows:
impl List {
// unrelated code not shown
fn tail(&self) -> Self {
match *self {
Self::Cons(_, ref tail) => tail,
nil => nil,
}
}
}
But I get the following compiler error:
error[E0308]: mismatched types
--> .\ee-enum-recall-linked-lists.rs:32:40
|
30 | fn tail(&self) -> Self {
| ---- expected `List` because of return type
31 | match *self {
32 | Self::Cons(_, ref tail) => tail,
| ^^^^ expected enum `List`, found `&Box<List>`
|
= note: expected enum `List`
found reference `&Box<List>`
Which is baffling, because some other code I'd written in this same style to attach a length()
method worked, and made me believe that the variable tail
there is actually of type List
.
impl List {
// unrelated code not shown
fn length(&self) -> i32 {
match *self {
Self::Cons(_, ref tail) => 1 + tail.length(),
_ => 0,
}
}
}
So, I'm wondering:
- What is the type of the value held by the variable
tail
there, really? - Why does
tail.length()
work iftail
isn't aList
? - How do I match down to the list contained in
tail
?