Skip to content

Instantly share code, notes, and snippets.

@ibrahim-eshag
Last active September 4, 2025 16:07
Show Gist options
  • Select an option

  • Save ibrahim-eshag/36c307a63a51ab4fab1d42d343454980 to your computer and use it in GitHub Desktop.

Select an option

Save ibrahim-eshag/36c307a63a51ab4fab1d42d343454980 to your computer and use it in GitHub Desktop.
fundamental concepts in rust
// 1. Entry point: main function
fn main() {
// 2. Variables and mutability
let x = 5; // Immutable by default
let mut y = 10; // Mutable variable
// 3. Data types
let int_val: i32 = 42; // 32-bit signed integer
let float_val: f64 = 3.14; // 64-bit float
let is_active: bool = true; // Boolean
let letter: char = 'R'; // Character
// 4. Constants
const PI: f64 = 3.14159; // Must have type, all caps
// 5. Shadowing
let x = x + 1; // x is now 6
// 6. Control flow: if/else
if x < y {
println!("x is less than y");
} else {
println!("x is not less than y");
}
// 7. Looping
for i in 0..5 { // Range: 0,1,2,3,4
println!("For loop iteration: {}", i);
}
let mut count = 0;
while count < 3 { // While loop
println!("While loop count: {}", count);
count += 1;
}
// 8. Functions
let sum = add(2, 3); // Call function
println!("Sum is {}", sum);
// 9. Ownership, borrowing, and references
let s = String::from("hello"); // s owns the String
takes_ownership(s); // s is moved, can't use s after this
let n = 5;
makes_copy(n); // i32 implements Copy, n still usable
/*
Move: Ownership is transferred (e.g., String). The original variable can’t be used after.
Copy: A duplicate is made (e.g., i32). The original variable remains usable.
Types that implement the Copy trait (like numbers) are copied; types that don’t (like String, Vec) are moved.
*/
// Borrowing with references
let t = String::from("world");
let len = calculate_length(&t); // borrow t, t not moved
println!("Length: {}", len);
// 10. Slices
let arr = [1, 2, 3, 4, 5];
let slice = &arr[1..3]; // Slice: [2,3]
println!("Slice: {:?}", slice);
// 11. Structs
let user = User {
username: String::from("alice"),
active: true,
age: 30,
};
println!("User: {}, active: {}, age: {}", user.username, user.active, user.age);
// 12. Enums
let color = Color::Red;
match color {
Color::Red => println!("Color is Red"),
Color::Green => println!("Color is Green"),
Color::Blue => println!("Color is Blue"),
}
// 13. Option and Result types
let maybe_value = Some(10);
if let Some(v) = maybe_value {
println!("Option has value: {}", v);
}
let result = safe_divide(6, 2);
match result {
Ok(val) => println!("Division result: {}", val),
Err(e) => println!("Error: {}", e),
}
// 14. Vectors
let mut v = Vec::new();
v.push(1);
v.push(2);
println!("Vector: {:?}", v);
// 15. Pattern matching
let num = 1;
match num {
1 => println!("One"),
2 | 3 => println!("Two or Three"),
_ => println!("Other"),
}
// 16. Traits and Implementations
let p = Point { x: 1.0, y: 2.0 };
println!("Distance from origin: {}", p.distance_from_origin());
// 17. Generics
let a = GenericStruct { value: 42 };
let b = GenericStruct { value: "hello" };
a.print_value();
b.print_value();
// 18. Error handling with panic and unwrap
// let fail = vec![1,2];
// println!("{}", fail[99]); // panics at runtime
let num_str = "42";
let parsed: i32 = num_str.parse().unwrap(); // unwraps Result, panics if error
println!("Parsed number: {}", parsed);
// 19. Modules (see below for module syntax)
my_module::greet();
}
// 8. Function definition
fn add(a: i32, b: i32) -> i32 {
a + b
}
// 9. Ownership example
fn takes_ownership(s: String) {
println!("Owned String: {}", s);
}
fn makes_copy(n: i32) {
println!("Copied integer: {}", n);
}
fn calculate_length(s: &String) -> usize { // Borrowed reference
s.len()
}
// 11. Structs
struct User {
username: String,
active: bool,
age: u32,
}
// 12. Enums
enum Color {
Red,
Green,
Blue,
}
// 13. Option and Result types
fn safe_divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err(String::from("Division by zero"))
} else {
Ok(a / b)
}
}
// 16. Traits and Implementations
struct Point {
x: f64,
y: f64,
}
trait Distance {
fn distance_from_origin(&self) -> f64;
}
impl Distance for Point {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
// 17. Generics
struct GenericStruct<T> {
value: T,
}
impl<T: std::fmt::Display> GenericStruct<T> {
fn print_value(&self) {
println!("Generic value: {}", self.value);
}
}
// 19. Modules
mod my_module {
pub fn greet() {
println!("Hello from my_module!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment