Complete reference for Rust standard library — memory safety, ownership, traits, collections, concurrency, and error handling with copy-paste examples.
Part of The Direct Path to Linux Ubuntu — free for all.
Save as main.rs inside a Cargo project and run with cargo run.
Ownership, borrowing, and basic Rust syntax.
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list { if item > largest { largest = item; } }
largest
}
fn main() {
let s1 = String::from("Hello, Rust!");
let s2 = s1.clone();
println!("{} and {}", s1, s2);
let s3 = String::from("MyWebUniversity");
println!("'{}' has {} chars", s3, s3.len());
let numbers = vec![34, 50, 25, 100, 65];
println!("Largest: {}", largest(&numbers));
// FizzBuzz with match
for n in 1..=15 {
println!("{}", match (n % 3, n % 5) {
(0, 0) => String::from("FizzBuzz"),
(0, _) => String::from("Fizz"),
(_, 0) => String::from("Buzz"),
_ => n.to_string(),
});
}
}
// cargo runRust structs, impl blocks, enums, and exhaustive match.
#[derive(Debug, Clone)]
struct Point { x: f64, y: f64 }
impl Point {
fn new(x: f64, y: f64) -> Self { Point { x, y } }
fn distance(&self, other: &Point) -> f64 {
((self.x-other.x).powi(2) + (self.y-other.y).powi(2)).sqrt()
}
}
#[derive(Debug)]
enum Shape {
Circle { center: Point, radius: f64 },
Rectangle { top_left: Point, bottom_right: Point },
Triangle(Point, Point, Point),
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle { radius, .. } => std::f64::consts::PI * radius * radius,
Shape::Rectangle { top_left, bottom_right } =>
(bottom_right.x-top_left.x).abs() * (bottom_right.y-top_left.y).abs(),
Shape::Triangle(a,b,c) => {
let (ab,bc,ca) = (a.distance(b), b.distance(c), c.distance(a));
let s = (ab+bc+ca)/2.0;
(s*(s-ab)*(s-bc)*(s-ca)).sqrt()
}
}
}
fn name(&self) -> &str {
match self { Shape::Circle{..}=>"Circle", Shape::Rectangle{..}=>"Rectangle", Shape::Triangle(..)=>"Triangle" }
}
}
fn main() {
let shapes = vec![
Shape::Circle { center: Point::new(0.,0.), radius: 5. },
Shape::Rectangle { top_left: Point::new(0.,6.), bottom_right: Point::new(4.,0.) },
Shape::Triangle(Point::new(0.,0.), Point::new(3.,0.), Point::new(0.,4.)),
];
for s in &shapes { println!("{:12} area = {:.4}", s.name(), s.area()); }
let largest = shapes.iter().max_by(|a,b| a.area().partial_cmp(&b.area()).unwrap());
println!("Largest: {}", largest.unwrap().name());
}
// cargo runDefine and implement Rust traits with default methods.
use std::fmt;
trait Summary {
fn summarize(&self) -> String;
fn word_count(&self) -> usize { self.summarize().split_whitespace().count() }
}
#[derive(Debug)]
struct Article { title: String, author: String, content: String }
#[derive(Debug)]
struct Tweet { username: String, message: String }
impl Summary for Article {
fn summarize(&self) -> String {
format!("{} by {} — {:.50}...", self.title, self.author, self.content)
}
}
impl Summary for Tweet {
fn summarize(&self) -> String { format!("@{}: {}", self.username, self.message) }
}
impl fmt::Display for Article {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Article({})", self.title) }
}
fn notify(item: &impl Summary) { println!("Breaking: {}", item.summarize()); }
fn largest_summary<T: Summary>(items: &[T]) -> &T {
items.iter().max_by_key(|i| i.word_count()).unwrap()
}
fn main() {
let article = Article { title:"Rust Tops Survey".into(), author:"MyWebUniversity".into(),
content:"Eighth year in a row Rust is the most loved language".into() };
let tweets = vec![
Tweet { username:"alice".into(), message:"Loving Rust ownership".into() },
Tweet { username:"bob".into(), message:"cargo test passed".into() },
Tweet { username:"carol".into(), message:"Pattern matching is elegant and expressive".into() },
];
notify(&article);
for t in &tweets { notify(t); }
println!("Most words: {}", largest_summary(&tweets).summarize());
println!("Display: {}", article);
}
// cargo runRust's lazy iterator chains — map, filter, fold, collect.
fn main() {
let numbers: Vec<i32> = (1..=20).collect();
let squares_of_evens: Vec<i32> = numbers.iter()
.filter(|&&n| n % 2 == 0)
.map(|&n| n * n)
.collect();
println!("Squares of evens: {:?}", squares_of_evens);
let product: i64 = (1..=10).fold(1i64, |acc,n| acc * n);
println!("10! = {}", product);
let names = vec!["Alice", "Bob", "Carol"];
let scores = vec![95u32, 87, 92];
let result: Vec<String> = names.iter().zip(scores.iter())
.enumerate()
.map(|(i,(name,score))| format!("{}. {} scored {}", i+1, name, score))
.collect();
result.iter().for_each(|s| println!("{}", s));
let sentences = vec!["hello world", "rust is great"];
let words: Vec<&str> = sentences.iter().flat_map(|s| s.split_whitespace()).collect();
println!("Words: {:?}", words);
let threshold = 50i32;
let multiples: Vec<i32> = (1..=100).filter(|n| n % 7 == 0 && *n > threshold).collect();
println!("Mult of 7 above {}: {:?}", threshold, multiples);
let running_sum: Vec<i32> = (1..=5)
.scan(0i32, |acc,x| { *acc += x; Some(*acc) })
.collect();
println!("Running sum: {:?}", running_sum);
}
// cargo runIdiomatic Rust error handling with From, Display, and ?
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum MyError {
Parse(ParseIntError),
Range { value: i64, min: i64, max: i64 },
Io(std::io::Error),
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MyError::Parse(e) => write!(f, "parse error: {}", e),
MyError::Range{value,min,max} => write!(f, "{} not in [{},{}]", value, min, max),
MyError::Io(e) => write!(f, "I/O: {}", e),
}
}
}
impl From<ParseIntError> for MyError { fn from(e: ParseIntError) -> Self { MyError::Parse(e) } }
impl From<std::io::Error> for MyError { fn from(e: std::io::Error) -> Self { MyError::Io(e) } }
fn parse_score(s: &str) -> Result<u32, MyError> {
let n: i64 = s.trim().parse::<i64>()?;
if n < 0 || n > 100 {
return Err(MyError::Range { value: n, min: 0, max: 100 });
}
Ok(n as u32)
}
fn process_scores(inputs: &[&str]) -> Result<f64, MyError> {
let scores: Result<Vec<u32>, _> = inputs.iter().map(|s| parse_score(s)).collect();
let scores = scores?;
let sum: u32 = scores.iter().sum();
Ok(sum as f64 / scores.len() as f64)
}
fn main() {
// Individual parsing
for input in &["95", "abc", "-5", "105", "87"] {
match parse_score(input) {
Ok(s) => println!("Score: {}", s),
Err(e) => println!("Error: {}", e),
}
}
// Batch processing
match process_scores(&["95", "87", "92", "78"]) {
Ok(avg) => println!("Average: {:.2}", avg),
Err(e) => println!("Batch error: {}", e),
}
match process_scores(&["95", "abc", "92"]) {
Ok(avg) => println!("Average: {:.2}", avg),
Err(e) => println!("Batch error: {}", e),
}
}
// cargo run