Rust Reference
Run Rust examples for parsing with Result, splitting key-value text, and comparing ordered maps.
Run the examples
Save each example as main.rs and run rustc main.rs, then ./main on macOS or Linux. The examples use the Rust standard library.
Parse a number with Result
Parsing with u16 checks both syntax and representable range. Match on Ok or Err to keep invalid input from turning into a default value unnoticed.
fn main() {
for input in ["8080", "65536", "oops"] {
match input.parse::<u16>() {
Ok(port) => println!("port: {port}"),
Err(_) => println!("invalid: {input}"),
}
}
}Expected output
port: 8080
invalid: 65536
invalid: oopsCommon mistake
Parsing a u16 does not enforce application rules such as rejecting port 0. Add those checks after parsing.
Split at the first equals sign
split_once returns borrowed slices on each side of the first delimiter. Any later equals signs remain in the value.
fn main() {
if let Some((key, value)) = "MODE=fast=local".split_once('=') {
println!("{key}: {value}");
}
}Expected output
MODE: fast=localCommon mistake
This example handles simple key-value lines. Quoting, escapes and variable expansion require a format-specific parser.
Compare values in key order
BTreeMap iterates in key order. Use it when a report must list changed keys consistently, then handle missing keys explicitly.
use std::collections::BTreeMap;
fn main() {
let before = BTreeMap::from([("timeout", 10), ("port", 80)]);
let after = BTreeMap::from([("port", 8080), ("timeout", 0)]);
for (key, old) in &before {
if let Some(current) = after.get(key) {
if current != old {
println!("{key}: {old} -> {current}");
}
}
}
}Expected output
port: 80 -> 8080
timeout: 10 -> 0Common mistake
The example checks existing keys for changes. To find added keys, also iterate over the keys in the new map.