Reputation: 166
I have a struct with two fields, state and children. Children is an option that contains a vector of children. I am using if let syntax to deconstruct this option back to the vector.
fn main() {
let mut root = Node::new2d(3);
loop {
root.calc_scores(100);
if let Some(mut children) = root.children {
let child = children.pop();
root = Node {
state: child.0,
children: None,
}
}
root.make_children();
}
}
struct Node<T> {
state: T,
children: Option<Vec<(T, i32)>>,
}
The above code doesn't compile. It complains that child is of type Option<(Board2d,i32)>
.
Why is child still wrapped up in an option enum? Doesn't if let Some(mut children) = root.children{}
take the vector out of the Option enum?
Upvotes: 0
Views: 323
Reputation: 17186
The pop
method on a Vec
returns an Option
, because the Vec
can actually be empty and thus return None
, you should check that too.
That being said, Option<Vec<_>>
is not something you will often need. It only makes sense if you really want a difference between an empty vector and no vector at all, which doesn't seem to be the case here. so you'd end up with something as follows:
fn main() {
let mut root = Node::new2d(3);
loop {
root.calc_scores(100);
if let Some(child) = root.children.pop() {
root = Node {
state: child.0,
children: vec![],
}
}
root.make_children();
}
}
struct Node<T> {
state: T,
children: Vec<(T, i32)>,
}
Upvotes: 5