Rust: More snippets – code examples
- Hello World
- Variables and types
- if / else if / else
- for loop
- Function with a return value
- Reading and writing a file
- Reading a file line by line
- Generic function with a trait bound
- Display for your own types
- Iterator chains
- Splitting and parsing a CSV line
- Counting words
- Command-line arguments
- Writing a unit test
Hello World
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
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
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
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
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
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
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
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
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
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
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
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
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
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.