Click on a topic to expand and learn in detail.
fn main() {
println!("Hello, Rust!");
}
Rust is fast, safe, and used for system-level programming.
let x = 5; // immutable
let mut y = 10; // mutable
let name: &str = "Alice"; // string slice
let pi: f64 = 3.14; // float
Variables are immutable by default. Rust has strong static typing.
// Arithmetic
let sum = 5 + 3;
// Comparison
let is_adult = x >= 18;
// Logical
let flag = is_adult && true;
Rust supports arithmetic, comparison, and logical operators.
if x >= 18 {
println!("Adult");
} else {
println!("Minor");
}
// match (like switch)
match x {
18 => println!("Exactly 18"),
_ => println!("Other age"),
}
Use if-else or match for conditional logic.
// for loop
for i in 0..5 {
println!("{}", i);
}
// while loop
let mut j = 0;
while j < 5 {
println!("{}", j);
j += 1;
}
// loop (infinite, break to exit)
let mut k = 0;
loop {
println!("{}", k);
k += 1;
if k == 5 { break; }
}
Rust provides for, while, and loop.
fn add(a: i32, b: i32) -> i32 {
return a + b;
}
println!("{}", add(5,3));
Functions are reusable blocks that can return values.
// Ownership example
let s1 = String::from("Hello");
let s2 = s1; // s1 is moved, s2 owns the value
// Borrowing
let s3 = &s2; // reference, no ownership transfer
Rust uses ownership and borrowing to manage memory safely.
// Struct
struct Person { name: String, age: u32 }
let p = Person { name: String::from("Alice"), age: 25 };
// Enum
enum Direction { Up, Down, Left, Right }