It is said that unwrap is unsafe and it should be avoided if possible.
While I was constructing a linked list, I found an unwrap inevitable.
My question is, is it possible to remove this unwrap or is there any theoretical reason that it is not possible?
pub struct Node {
pub value: i32,
pub next: Option<Box<Node>>
}
let mut sentinel: Box<Node> = Box::new(Node {
value: -1,
next: None,
});
let mut current: &mut Box<Node> = &mut sentinel;
loop {
... // break or set value
current.next = Some(Box::new(Node {
value: value,
next: None,
}));
current = current.next.as_mut().unwrap();
}
sentinel.next
I am not expecting an answer which adds a meaningless branch like let-else or if-let.
Note: For the other way around, it seems that replace is useful.
self.root = Some(Box::new(Node {
value: value,
next: ::std::mem::replace(&mut self.root, None),
}));
New contributor
Keita ODA is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.