使用向量作为堆栈时(存储被推送和弹出的状态).
while stack.len() != 0 {
let state = stack.pop().unwrap();
// ... optionally push other states onto the stack.
}
Run Code Online (Sandbox Code Playgroud)
在Rust中有一个不那么冗长的方法吗?
小智 6
您可以使用循环pop()返回an Option<T>和匹配的事实while let:
while let Some(state) = stack.pop() {
// ... fine to call stack.push() here
}
Run Code Online (Sandbox Code Playgroud)
while let对以下内容的贬低:
loop {
match stack.pop() {
Some(state) => {
// ... fine to call stack.push() here
}
_ => break
}
}
Run Code Online (Sandbox Code Playgroud)