Because of the Some(ref v)
, you were borrowing the value. You then didn't use it, so Some(_)
would have been fine. But really, you do want to take the value. So what you actually want is to shift the take()
outside the match.
Here's the end result:
pub struct Node<T> {
next: Option<~Node<T>>,
data: Option<T>
}
/** Attach a node as the 'next' node in this chain */
pub fn push<'a>(&'a mut self, value: T) -> &'a mut ~Node<T> {
match self.next.take() {
None => self.push_node(~Node::new(value)),
Some(v) => {
let mut next = ~Node::new(value);
next.push_node(v);
self.push_node(next);
}
}
match self.next {
Some(ref mut t) => t,
None => unreachable!(),
}
// Sure, you could replace those four lines with self.next.as_mut().unwrap(),
// but I have a slight leaning towards highlighting the unreachable nature of
// the None branch. It makes it more explicit.
// Others will doubtless disagree with me on that point.
}
You could also have gone for Some(ref mut v)
and manipulated that &mut ~Node<T>
value directly, but that would presumably require altering how push_node
works. (You haven't shown the code for it so I can only guess what it does.)
A few other stylistic changes I've made:
- four spaces, not two;
- don't prefix things with underscore (Rust has sufficient privacy control, no need to use underscores);
- no parentheses around the
if
expression (well, now that's been replaced withmatch
, so it doesn't matter); - if there is but one statement in a match branch, there's no need for the curly braces around it—just use a comma after it and that's it,
return x;
can be written as justx
when it's at the end of a function.