我有一个包含两个字段state和children的结构体。Children 是一个包含孩子向量的选项。我正在使用 if let 语法将此选项解构回向量。
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)>>,
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不能编译。它抱怨 child 是 类型Option<(Board2d,i32)>。为什么 child 仍然包含在选项枚举中?不会if let Some(mut children) = root.children{}从 Option 枚举中取出向量吗?
该pop方法在Vec返回的Option,因为Vec实际上是空的,因此回报None,你应该检查这一点。
话虽如此,这Option<Vec<_>>不是您经常需要的东西。只有当你真的想要一个空向量和根本没有向量之间的区别时才有意义,这似乎不是这种情况。所以你最终会得到如下结果:
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)>,
}
Run Code Online (Sandbox Code Playgroud)