RRust By Example
intermediateCompound Types

Vec Methods

Common Vec methods: retain, dedup, windows, chunks.

Vec Methods

Common Vec methods: retain, dedup, windows, chunks.

Difficulty

Intermediate

Code

rust
fn main() {
    // retain: keep elements matching predicate
    let mut v = vec![1, 2, 3, 4, 5, 6];
    v.retain(|&x| x % 2 == 0);
    println!("evens: {:?}", v);

    // dedup: remove consecutive duplicates
    let mut v = vec![1, 1, 2, 2, 3, 3, 3];
    v.dedup();
    println!("dedup: {:?}", v);

    // windows: sliding window
    let v = vec![1, 2, 3, 4, 5];
    for w in v.windows(3) {
        println!("window: {:?}", w);
    }

    // chunks: non-overlapping chunks
    let v = vec![1, 2, 3, 4, 5, 6, 7];
    for c in v.chunks(3) {
        println!("chunk: {:?}", c);
    }
}

Explanation

retain, dedup, windows, chunks for efficient Vec operations.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the compound-types category to build a complete understanding of this topic.

More Compound Types Examples