1. Hello World (hello.
rs)
The most basic Rust program to print "Hello, World!":
fn main() {
println!("Hello, World!");
}
Compile & Run:
rustc [Link]
./hello
2. Variables and Data Types ([Link])
fn main() {
let integer_var: i32 = 10;
let float_var: f64 = 3.14;
let bool_var: bool = true;
let char_var: char = 'R';
println!("Integer: {}", integer_var);
println!("Float: {}", float_var);
println!("Boolean: {}", bool_var);
println!("Character: {}", char_var);
}
3. Conditional Statements ([Link])
fn main() {
let number = 5;
if number % 2 == 0 {
println!("{} is even", number);
} else {
println!("{} is odd", number);
}
}
4. Loops ([Link])
fn main() {
// For loop
for i in 1..6 {
println!("For loop iteration: {}", i);
}
// While loop
let mut count = 0;
while count < 5 {
println!("While loop iteration: {}", count);
count += 1;
}
}
5. Functions ([Link])
fn main() {
let result = add(5, 3);
println!("Sum is: {}", result);
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
6. Structs and Methods ([Link])
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
[Link] * [Link]
}
}
fn main() {
let rect = Rectangle { width: 10, height: 5 };
println!("Area of rectangle: {}", [Link]());
}
7. Enums and Pattern Matching ([Link])
enum Direction {
North,
South,
East,
West,
}
fn move_direction(dir: Direction) {
match dir {
Direction::North => println!("Moving North"),
Direction::South => println!("Moving South"),
Direction::East => println!("Moving East"),
Direction::West => println!("Moving West"),
}
}
fn main() {
move_direction(Direction::East);
}
8. Using Vectors ([Link])
fn main() {
let mut numbers = vec![1, 2, 3];
[Link](4);
for number in &numbers {
println!("Number: {}", number);
}
}
9. Reading Input from User ([Link])
use std::io;
fn main() {
let mut input = String::new();
println!("Enter your name: ");
io::stdin().read_line(&mut input)
.expect("Failed to read line");
println!("Hello, {}!", [Link]());
}
10. Error Handling with Result (error_handling.rs)
use std::fs::File;
fn main() {
match File::open("[Link]") {
Ok(_) => println!("File opened successfully."),
Err(e) => println!("Failed to open file: {}", e),
}
}
How to run these examples:
Install Rust via rustup
Save the code to a file with .rs extension.
Compile with rustc [Link]
Run the executable (./filename on Unix/Linux/macOS, [Link] on Windows)
Let me know if you need explanations or more advanced examples!