Learn RUST with Real Code Examples
Updated Nov 17, 2025
Code Sample Descriptions
1
Rust Ownership Example
fn main() {
let mut numbers = vec![1, 2, 3, 4, 5];
println!("Original: {:?}", numbers);
let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect();
println!("Doubled: {:?}", doubled);
let sum: i32 = numbers.iter().sum();
println!("Sum: {}", sum);
numbers.push(6);
println!("Modified: {:?}", numbers);
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
#[test]
fn test_rectangle_area() {
let rect = Rectangle { width: 10, height: 20 };
assert_eq!(rect.area(), 200);
}
Demonstrates Rust's ownership system, iterators, and struct implementation with testing.
2
Rust Borrowing Example
fn main() {
let s = String::from("Hello");
print_length(&s);
println!("Original string: {}", s);
}
fn print_length(s: &String) {
println!("Length: {}", s.len());
}
Shows borrowing and references to avoid moving ownership.
3
Rust Trait Example
trait Greet {
fn greet(&self);
}
struct Person {
name: String,
}
impl Greet for Person {
fn greet(&self) {
println!("Hello, {}!", self.name);
}
}
fn main() {
let person = Person { name: String::from("Alice") };
person.greet();
}
Implements a trait for a struct to define common behavior.
4
Rust Enum Example
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn process(msg: Message) {
match msg {
Message::Quit => println!("Quit message"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Text: {}", text),
}
}
fn main() {
process(Message::Move { x: 10, y: 20 });
process(Message::Write(String::from("Hello")));
}
Demonstrates enums with associated data and pattern matching.
5
Rust Result and Error Handling
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err(String::from("Division by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10, 2) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}
}
Demonstrates using Result for error handling in Rust.
6
Rust Iterator Example
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let evens: Vec<i32> = numbers.iter().filter(|&&x| x % 2 == 0).map(|x| x * x).collect();
println!("Evens squared: {:?}", evens);
}
Uses iterators and map/filter to transform a vector.
7
Rust Struct with Methods
struct Circle {
radius: f64,
}
impl Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
fn circumference(&self) -> f64 {
2.0 * std::f64::consts::PI * self.radius
}
}
fn main() {
let c = Circle { radius: 5.0 };
println!("Area: {}", c.area());
println!("Circumference: {}", c.circumference());
}
Defines a struct with methods and demonstrates usage.
8
Rust String Manipulation
fn main() {
let mut s = String::from("Hello");
s.push_str(", World!");
println!("{}", s);
let slice = &s[0..5];
println!("Slice: {}", slice);
}
Demonstrates basic string operations and slicing.
9
Rust Generic Function
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut max = list[0];
for &item in list.iter() {
if item > max {
max = item;
}
}
max
}
fn main() {
let nums = vec![10, 20, 5, 30];
println!("Largest: {}", largest(&nums));
}
Shows a generic function to find the largest element in a list.
10
Rust Closures Example
fn main() {
let factor = 3;
let multiply = |x| x * factor;
println!("Result: {}", multiply(10));
}
Demonstrates using closures to capture variables and perform operations.