Rev And DoubleEndedIterator Walk Back To Front
Reverse traversal with rev works on any DoubleEndedIterator, so Vec iterators, ranges, and string chars can be consumed back to front.
Code
fn main() {
let history = vec!["save", "build", "test", "deploy"];
// rev():从尾到头遍历,像 tail 一样先看最新记录
println!("latest first:");
for step in history.iter().rev() {
println!(" {step}");
}
// rev 需要 DoubleEndedIterator:iter() 借用迭代器天然支持
// into_iter() 得到的消费式迭代器同样双端,从尾部逐个弹出
let mut owned = history.clone().into_iter().rev();
println!("pop from back: {:?}", owned.next());
println!("pop again: {:?}", owned.next());
// 字符串与 range 同样支持反向
let word = "rust";
let backwards: String = word.chars().rev().collect();
println!("{word} reversed is {backwards}");
let countdown: Vec<u32> = (1..=3).rev().collect();
println!("countdown: {countdown:?}");
}How it works
Rev And DoubleEndedIterator Walk Back To Front comes down to the function main.
Iteration happens inside for step in history.iter().rev() — everything outside it runs once.
Using it
Running the file prints labeled results such as latest first:, pop from back:, pop again: — each operation’s effect is visible in the output.
Key statements
let backwards: String = word.chars().rev().collect();
let countdown: Vec<u32> = (1..=3).rev().collect();
for step in history.iter().rev() {
println!(" {step}");
}
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Rev And DoubleEndedIterator Walk Back To Front print when run?
- No setup needed: run the file and look for labeled lines like `latest first:`, `pop from back:`, `pop again:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.