How to initialize a vector with a range of numbers in Rust

1 Answer

0 votes
// Demonstrating several ways to build a vector containing a range of numbers.
// Each function shows a different style that experienced developers commonly use.

// Build a vector using the standard range syntax.
// This is concise, expressive, and uses built‑in iteration.
fn make_range_basic(start: i32, end: i32) -> Vec<i32> {
    (start..end).collect()
}

// Build a vector using a manual loop.
// Clear and flexible; works well when adding extra logic.
fn make_range_loop(start: i32, end: i32) -> Vec<i32> {
    let mut values: Vec<i32> = Vec::with_capacity((end - start) as usize);
    for n in start..end {
        values.push(n);
    }
    values
}

// Build a vector using iterator methods.
// Shows how to use map() and collect() together.
fn make_range_map(start: i32, end: i32) -> Vec<i32> {
    (0..(end - start)).map(|i| start + i).collect()
}

// Build a vector using a generator‑style function (Rust iterators).
// Demonstrates custom iteration logic.
fn make_range_custom_iter(start: i32, end: i32) -> Vec<i32> {
    struct RangeIter {
        current: i32,
        end: i32,
    }

    impl Iterator for RangeIter {
        type Item = i32;

        fn next(&mut self) -> Option<Self::Item> {
            if self.current < self.end {
                let value = self.current;
                self.current += 1;
                Some(value)
            } else {
                None
            }
        }
    }

    RangeIter { current: start, end }.collect()
}

// Print a vector for demonstration.
fn show(label: &str, values: &[i32]) {
    println!("{}: {:?}", label, values);
}

fn main() {
    let a: Vec<i32> = make_range_basic(1, 10);
    let b: Vec<i32> = make_range_loop(1, 10);
    let c: Vec<i32> = make_range_map(1, 10);
    let d: Vec<i32> = make_range_custom_iter(1, 10);

    show("basic range", &a);
    show("loop", &b);
    show("map", &c);
    show("custom iterator", &d);
}


/*
run:

basic range: [1, 2, 3, 4, 5, 6, 7, 8, 9]
loop: [1, 2, 3, 4, 5, 6, 7, 8, 9]
map: [1, 2, 3, 4, 5, 6, 7, 8, 9]
custom iterator: [1, 2, 3, 4, 5, 6, 7, 8, 9]

*/

 



answered Aug 18 by avibootz
...