@BallPointtBen关于使用peekable
的 comments 的一个实际例子是:
fn main() {
let data = "Hello, world!";
let mut iter = data.chars().peekable();
while let Some(¤t) = iter.peek() {
// Do something with the current character without consuming it
println!("Current character: {}", current);
// Now consume the character
iter.next();
// You can also peek the next character without consuming it
if let Some(&next) = iter.peek() {
println!("Next character: {}", next);
} else {
println!("This was the last character.");
}
}
}
Rust Playground Example个
输出:
Current character: H
Next character: e
Current character: e
Next character: l
Current character: l
Next character: l
Current character: l
Next character: o
Current character: o
Next character: ,
Current character: ,
Next character:
Current character:
Next character: w
Current character: w
Next character: o
Current character: o
Next character: r
Current character: r
Next character: l
Current character: l
Next character: d
Current character: d
Next character: !