RsRust

Rust: More snippets – code examples

Contents

Hello World

Basics#println#output#mainCompare in all languages
Use case: A first test of whether Rust is installed correctly.
fn main() {
    println!("Hello World!");
}

main is the entry point, println! is a macro (recognizable by the !). Run it with cargo run or rustc hallo.rs.

Variables and types

Basics#let#mut#type#shadowingCompare in all languages
Use case: Storing values; types are fixed, and mutability must be allowed explicitly.
fn main() {
    let name = "Ada";
    let mut alter: u32 = 36;
    let groesse = 1.68;
    let aktiv = true;
    alter += 1;
    println!("{name} {alter} {groesse} {aktiv}");
    let x = 5;
    let x = x * 2;          // shadowing
    println!("{x}");
}

let is immutable, mut allows changes. The type is inferred (&str, f64, bool); with shadowing you can rebind a name.

if / else if / else

Control flow#if#conditionCompare in all languages
Use case: Reacting differently, e.g. calculating grades or price tiers.
fn main() {
    let punkte = 73;
    if punkte >= 90 {
        println!("very good");
    } else if punkte >= 70 {
        println!("good");
    } else {
        println!("needs improvement");
    }
}

No parentheses around the condition, and it must be a bool. if is also an expression: let note = if ... { "a" } else { "b" };.

for loop

Control flow#for#loop#rangeCompare in all languages
Use case: Processing every element of a list or repeating n times.
fn main() {
    for i in 0..3 {
        println!("Round {i}");
    }
    for frucht in ["Apple", "Pear"] {
        println!("{frucht}");
    }
}

0..3 yields 0, 1, 2 (0..=3 would include the 3). The second loop runs directly over an array.

Function with a return value

Functions#fn#return#functionCompare in all languages
Use case: Bundling recurring logic, e.g. greeting texts or calculations.
fn begruesse(name: &str, gruss: &str) -> String {
    format!("{gruss}, {name}!")
}

fn main() {
    println!("{}", begruesse("Ada", "Hello"));
    println!("{}", begruesse("Linus", "Hi"));
}

The last expression without a semicolon is the return value. Rust has no default parameter values; people use Option or builders instead.

Reading and writing a file

Files#fs#file#ioCompare in all languages
Use case: Saving and loading logs, configurations, or text data.
use std::fs;
use std::io;

fn main() -> io::Result<()> {
    fs::write("notizen.txt", "Line 1\nLine 2\n")?;
    let inhalt = fs::read_to_string("notizen.txt")?;
    for zeile in inhalt.lines() {
        println!("{}", zeile.trim());
    }
    Ok(())
}

fs::write and fs::read_to_string do everything in one line. ? passes I/O errors on to the caller; the file is closed automatically through Drop.

Reading a file line by line

Files#bufreader#lines#file
Use case: Processing large log files without loading everything into memory.
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() -> std::io::Result<()> {
    let datei = File::open("log.txt")?;
    for (nr, zeile) in BufReader::new(datei).lines().enumerate() {
        let zeile = zeile?;
        if zeile.contains("ERROR") {
            println!("{}: {}", nr + 1, zeile);
        }
    }
    Ok(())
}

BufReader reads with buffering; lines() yields an io::Result<String> per line, which is unwrapped with ?.

Generic function with a trait bound

Traits#generics#trait#display
Use case: Writing one function for many types (output, comparison, sums) without duplicating code.
use std::fmt::Display;

fn drucke_alle<T: Display>(items: &[T]) {
    for (i, item) in items.iter().enumerate() {
        println!("{}: {}", i + 1, item);
    }
}

fn main() {
    drucke_alle(&["Apple", "Pear"]);
    drucke_alle(&[1.5, 2.5]);
}

T: Display requires that the type can be printed. The compiler generates one optimized version per type (monomorphization), with no runtime cost.

Display for your own types

Traits#display#fmt#trait
Use case: Printing your own types nicely, e.g. in logs or error messages.
use std::fmt;

struct Punkt {
    x: i32,
    y: i32,
}

impl fmt::Display for Punkt {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

fn main() {
    let p = Punkt { x: 3, y: -1 };
    println!("Point: {p}");                // Point: (3, -1)
    println!("{}", p.to_string().len());   // 7
}

If you implement Display, you get {} in println! and to_string() automatically.

Iterator chains

Iterators#iterator#filter#fold#sum
Use case: Filtering, transforming, and aggregating data, e.g. evaluating prices or measurements.
fn main() {
    let preise = [4.5, 12.0, 7.25, 30.0];
    let teuer: Vec<f64> = preise.iter().copied().filter(|&p| p > 10.0).collect();
    let summe: f64 = preise.iter().sum();
    let max = preise.iter().cloned().fold(f64::MIN, f64::max);
    println!("{:?} {} {}", teuer, summe, max);   // [12.0, 30.0] 53.75 30
}

Iterators are lazy and only run through collect, sum, or fold. f64 is not Ord, so for the maximum you need fold with f64::max.

Splitting and parsing a CSV line

Strings#split#parse#csv#text
Use case: Converting simple text formats (CSV, log lines, config entries) into values.
fn main() {
    let zeile = "Ada,36,London";
    let felder: Vec<&str> = zeile.split(',').collect();
    let alter: u32 = felder[1].parse().unwrap();
    println!("{} is {} and lives in {}", felder[0], alter, felder[2]);
}

split returns an iterator over text slices (&str) without copying. parse converts to the target type; in real code use ? or match instead of unwrap.

Counting words

Strings#hashmap#entry#sort#count
Use case: Text analysis, e.g. the most frequent words in a document.
use std::collections::HashMap;

fn main() {
    let text = "this is a test this is good";
    let mut zaehler: HashMap<&str, u32> = HashMap::new();
    for wort in text.split_whitespace() {
        *zaehler.entry(wort).or_insert(0) += 1;
    }
    let mut paare: Vec<_> = zaehler.into_iter().collect();
    paare.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
    println!("{:?}", &paare[..2]);   // [("is", 2), ("this", 2)]
}

The entry API creates missing entries with 0 and increments them. When sorting, then ensures a fixed, alphabetical order for equal counts.

Command-line arguments

Tools#cli#env#args
Use case: Building your own CLI tools that accept names, files, or options.
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    match args.get(1) {
        Some(name) => println!("Hello, {name}!"),
        None => eprintln!("Usage: {} <name>", args[0]),
    }
}

args[0] is the program name. Run it with cargo run -- Ada. For more complex options (flags, help), use the clap crate.

Writing a unit test

Tools#test#assert#cargo
Use case: Checking functions automatically so that refactorings do not introduce bugs.
pub fn ist_gerade(n: i32) -> bool {
    n % 2 == 0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn gerade_und_ungerade() {
        assert!(ist_gerade(4));
        assert!(!ist_gerade(7));
        assert_eq!(ist_gerade(0), true);
    }
}

Run it with cargo test. #[cfg(test)] ensures that the module is only compiled when testing.