Range Over Built in Rust

Here we use range to sum the numbers in a slice. Arrays work like this too.

fn main() {
    let nums = vec![2, 3, 4];
    let mut sum = 0;

    for num in &nums {
        sum += num;
    }
    println!("sum: {}", sum);

    for (i, num) in nums.iter().enumerate() {
        if *num == 3 {
            println!("index: {}", i);
        }
    }

    let kvs = [("a", "apple"), ("b", "banana")].iter().cloned().collect::<std::collections::HashMap<_, _>>();
    for (k, v) in &kvs {
        println!("{} -> {}", k, v);
    }

    for k in kvs.keys() {
        println!("key: {}", k);
    }

    for (i, c) in "go".chars().enumerate() {
        println!("{} {}", i, c);
    }
}

To run the program, put the code in main.rs and use cargo run if you’re using Cargo as your build system.

$ cargo run
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 g
1 o

In Rust, for loops iterate over iterators, which is a common pattern to iterate over the elements of various collections. Here, enumerate is used to get the index along with the item, and chars() is used to iterate over each character in a string.

Next example: Pointers.