I am practicing Rust by implementing a listed list, when I write the function insert_after
, I got a compiler error, but when I use take
method of Option, it disappears, I want to know why because i think that node.next
are all option, it should be assignable.
Thanks for any help ~~
pub struct LinkListNode<T> {
body: T,
next: LinkdListNodeLink<T>
}
type LinkdListNodeLink<T> = Option<Box<LinkListNode<T>>>;
pub struct LinkdList<T> {
head: LinkdListNodeLink<T>
}
impl <T: std::fmt::Debug> LinkdList<T> {
pub fn new() -> Self {
LinkdList { head: None }
}
pub fn insert_after(&mut self, value: T, index: u32) -> Result<(), u32> {
match self.head.as_mut() {
None => {
self.head = Some(Box::new( LinkListNode { body: value, next: None }));
return Ok(());
}
Some(mut node) => {
for i in 0..index {
match node.next.as_mut() {
Some(next_node) => {
node = next_node;
}
None => {
return Err(i);
}
}
}
let mut new_node = Box::new(LinkListNode { body: value, next: None });
new_node.next = node.next; // error disappears when i use node.next.take
node.next = Some(new_node);
return Ok(());
}
}
}
}