Rust examples

Practical, runnable Rust snippets. Click any example to open it in the interactive Rust playground, then edit the code and compile it with full compiler diagnostics.

fn main() {
    println!("Hello from Rust!");

    for i in 0..10 {
        println!("fib({}) = {}", i, fib(i));
    }
}

fn fib(n: u64) -> u64 {
    if n < 2 {
        n
    } else {
        fib(n - 1) + fib(n - 2)
    }
}

Run a Rust program that prints Hello World and computes Fibonacci numbers.

Open in Rust playground
use std::collections::HashMap;

fn main() {
    let words = ["banana", "apple", "cherry", "apple", "banana", "apple"];

    // Count occurrences with a HashMap.
    let mut counts: HashMap<&str, i32> = HashMap::new();
    for w in &words {
        *counts.entry(w).or_insert(0) += 1;
    }

    // Sort keys for stable output.
    let mut keys: Vec<&&str> = counts.keys().collect();
    keys.sort();

    for k in keys {
        println!("{:<8} {}", k, counts[*k]);
    }
}

Count word occurrences using a HashMap in Rust.

Open in Rust playground
fn main() {
    let nums = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    let sum_of_even_squares: i32 = nums
        .iter()
        .filter(|&&x| x % 2 == 0)
        .map(|&x| x * x)
        .sum();

    println!("nums: {:?}", nums);
    println!("sum of even squares: {}", sum_of_even_squares);

    let doubled: Vec<i32> = nums.iter().map(|x| x * 2).collect();
    println!("doubled: {:?}", doubled);
}

Transform and reduce a vector using Rust iterator adapters.

Open in Rust playground