✅ Concepts Covered
Variables & mutability
Data types & shadowing
Control flow (if, match)
Loops (for, while)
Functions
Ownership & borrowing
Vectors & slices
Structs & impl blocks
Enums & pattern matching
Traits & trait implementations
Result & Option
Basic error handling
use std::io;
// Define a struct
struct Person {
name: String,
age: u8,
}
impl Person {
fn greet(&self) {
println!("Hi, I'm {} and I'm {} years old.", [Link], [Link]);
}
}
// Define an enum
enum Status {
Online,
Offline,
Away,
}
impl Status {
fn show(&self) {
match self {
Status::Online => println!("Status: Online"),
Status::Offline => println!("Status: Offline"),
Status::Away => println!("Status: Away"),
}
}
}
// Trait example
trait Speak {
fn speak(&self);
}
impl Speak for Person {
fn speak(&self) {
println!("{} says: Hello!", [Link]);
}
}
// Function that returns Result
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err("Cannot divide by zero.".to_string())
} else {
Ok(a / b)
}
}
fn main() {
// Basic variables
let x = 10;
let mut y = 20;
y += x;
println!("x + y = {}", y);
// Input/output
println!("Enter your name:");
let mut name = String::new();
io::stdin().read_line(&mut name).unwrap();
let name = [Link]();
// Struct and method usage
let user = Person {
name: name.to_string(),
age: 30,
};
[Link]();
[Link]();
// Enums
let s = Status::Online;
[Link]();
// Control flow
if y > 25 {
println!("y is large");
}
// Loops and vectors
let nums = vec![1, 2, 3, 4, 5];
for n in &nums {
println!("Num: {}", n);
}
// Slice & while
let slice = &nums[1..4];
let mut i = 0;
while i < [Link]() {
println!("Slice[{}] = {}", i, slice[i]);
i += 1;
}
// Result and error handling
match divide(10.0, 2.0) {
Ok(result) => println!("10 / 2 = {}", result),
Err(e) => println!("Error: {}", e),
}
}
| Concept | Example Lines |
| -------------- | ------------------------------- |
| Variables | `let x = 10;` |
| Structs & impl | `struct Person`, `impl Person` |
| Enums | `enum Status` |
| Traits | `trait Speak` |
| Functions | `fn divide(...) -> Result<...>` |
| Ownership | `name: name.to_string()` |
| Borrowing | `&nums`, `&self` |
| Result / Error | `match divide(...)` |
| Vectors | `vec![1,2,3]`, slicing |
🛠 How to Run This
Install Rust from [Link]
Save this file as [Link]
Run it using:
bash
Copy code
rustc [Link] && ./main