Rust · Playground
Rust playground
Running Rust inside the browser is not available yet. Use this editor to write, then download the file and run it locally with rustc 1.94. The example snippets were verified that way.
// A tiny tide table: each entry is (hour, height in cm).
fn main() {
let tides = [(0, 112), (3, 245), (6, 118), (9, 251), (12, 109)];
let highest = tides.iter().max_by_key(|(_, h)| h).unwrap();
println!("Highest tide: {} cm at {}:00", highest.1, highest.0);
for (hour, height) in tides {
let bar = "#".repeat((height / 25) as usize);
println!("{:02}:00 {:>4} cm {}", hour, height, bar);
}
}
Output
Press Run to see the program’s output here.
Running Rust inside the browser is not available yet. Use this editor to write, then download the file and run it locally with rustc 1.94. The example snippets were verified that way.
Rust examples
Each one was run with rustc 1.94 before it was published. Load one, change it, run it.
- Rust · Count down with for and while
// Loops: a countdown with `for` over a range and a `while` that halves a number. fn main() { for n in (1..=5).rev() { println!("T-minus {}", n); } let mut width = 96; while width > 10 { width /= 2; println!("halved to {}", width); } } - Rust · Define and call a function
// Functions: parameters are typed, the last expression is the return value. fn area_cm2(width_cm: u32, height_cm: u32) -> u32 { width_cm * height_cm } fn describe(name: &str, area: u32) -> String { format!("{} covers {} cm2", name, area) } fn main() { let poster = area_cm2(42, 60); println!("{}", describe("poster", poster)); println!("{}", describe("postcard", area_cm2(10, 15))); } - Rust · Filter a Vec and count with a BTreeMap
// Collections: a Vec of readings and a BTreeMap that counts by category. use std::collections::BTreeMap; fn main() { let readings = vec![18, 23, 31, 27, 12, 35, 22]; let hot: Vec<&i32> = readings.iter().filter(|&&r| r >= 25).collect(); println!("hot days: {:?}", hot); println!("average: {}", readings.iter().sum::<i32>() / readings.len() as i32); let mut by_band: BTreeMap<&str, u32> = BTreeMap::new(); for r in &readings { let band = if *r < 20 { "cool" } else if *r < 30 { "mild" } else { "hot" }; *by_band.entry(band).or_insert(0) += 1; } for (band, count) in &by_band { println!("{}: {}", band, count); } } - Rust · Split, capitalise and replace text
// Strings: String owns its text, &str borrows it; chars() walks Unicode characters. fn main() { let title = String::from("river ferry timetable"); let words: Vec<&str> = title.split(' ').collect(); println!("{} words, {} bytes, {} chars", words.len(), title.len(), title.chars().count()); let capitalised: Vec<String> = words .iter() .map(|w| { let mut c = w.chars(); match c.next() { Some(first) => first.to_uppercase().collect::<String>() + c.as_str(), None => String::new(), } }) .collect(); println!("{}", capitalised.join(" ")); println!("{}", title.replace("ferry", "bus").to_uppercase()); } - Rust · A struct with an enum field and a match
// Structs and enums: data with methods, and a match that must cover every case. #[derive(Debug)] enum Status { Docked, Sailing { knots: u32 }, Delayed(u32), } struct Ferry { name: String, status: Status, } impl Ferry { fn report(&self) -> String { match &self.status { Status::Docked => format!("{} is docked", self.name), Status::Sailing { knots } => format!("{} is sailing at {} knots", self.name, knots), Status::Delayed(minutes) => format!("{} is delayed by {} min", self.name, minutes), } } } fn main() { let fleet = vec![ Ferry { name: String::from("Kestrel"), status: Status::Sailing { knots: 14 } }, Ferry { name: String::from("Heron"), status: Status::Docked }, Ferry { name: String::from("Osprey"), status: Status::Delayed(25) }, ]; for ferry in &fleet { println!("{}", ferry.report()); } println!("{:?}", fleet[0].status); }
How this page was checked. Every program on it was run with rustc 1.94 at build time by the publishing checks, and the output shown is what it printed. Running Rust inside the browser is not available yet, so the Run button is absent rather than pretending; copy the code and run it with rustc 1.94 locally.