shymeander on Nostr: ```rust fn main() { // Variables (immutable by default) let x = 5; let mut y = 1; // ...
```rust
fn main() {
// Variables (immutable by default)
let x = 5;
let mut y = 1; // mutable
// Types
let i: i32 = 42; // integers
let f: f64 = 3.14; // float
let b: bool = true;
let s: String = String::from("hello");
let slice: &str = "world";
// Vec (dynamic array)
let mut v: Vec<i32> = vec![1, 2, 3];
v.push(4);
// Ownership & Borrowing
let s1 = String::from("mine");
let s2 = &s1; // borrow (reference)
println!("{} {}", s1, s2);
// Pattern Matching
match x {
1 => println!("one"),
2..=5 => println!("2-5"),
_ => println!("other"),
}
// Option & Result for safety
let opt: Option<i32> = Some(42);
if let Some(n) = opt {
println!("{}", n);
}
// Structs & Impl
struct Point { x: i32, y: i32 }
impl Point {
fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
}
// Traits (interfaces)
trait Shape {
fn area(&self) -> f64;
}
// Closures
let add = |a, b| a + b;
// Iterators
let sum: i32 = (1..=5).sum();
}
```
fn main() {
// Variables (immutable by default)
let x = 5;
let mut y = 1; // mutable
// Types
let i: i32 = 42; // integers
let f: f64 = 3.14; // float
let b: bool = true;
let s: String = String::from("hello");
let slice: &str = "world";
// Vec (dynamic array)
let mut v: Vec<i32> = vec![1, 2, 3];
v.push(4);
// Ownership & Borrowing
let s1 = String::from("mine");
let s2 = &s1; // borrow (reference)
println!("{} {}", s1, s2);
// Pattern Matching
match x {
1 => println!("one"),
2..=5 => println!("2-5"),
_ => println!("other"),
}
// Option & Result for safety
let opt: Option<i32> = Some(42);
if let Some(n) = opt {
println!("{}", n);
}
// Structs & Impl
struct Point { x: i32, y: i32 }
impl Point {
fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
}
// Traits (interfaces)
trait Shape {
fn area(&self) -> f64;
}
// Closures
let add = |a, b| a + b;
// Iterators
let sum: i32 = (1..=5).sum();
}
```