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.

RustCli Tooling

Code

rustsnippet
22 lines
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

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.