Rust is supposedly a safe language, unlike C and its extensions.
snake_caselet x = 5; ←- here, x is a constantmut to make it mutable: let mut n = 10;let x: u8 = 12;let x = 12u8;let t = (16, 12, false, 3.1415);t.0, t.1, ...return (x, y);let (a, b, c) = tuple;as:```rust let a = 5u8; let b = 16u32; let c = a as u32 + b; ```
const PI: f32 = 3.14159;let v: [i32; 4] = [1, 2, 3, 4];println! macro is useful to print text to the screen.println!("x val: {x}");println!("x+2 is {}", x + 2);```rust
if a > b {
println!("a gt b");
} else if b > a{
println!("b gt a");
```
loop and break;for x in 0..5 and for x in 0..=5 for iterating inclusively```rust
let s = loop {
x += 1;
if x == 128 {
break "reached 128!";
}
};
println!("position: {}", s);
```
io::stdin().read_line(&mut n); match n { 5 => { println!("got 5"); } // mutiple options 10 | 15 | 20 => { println!("some multiple of 5"); } // bind match to variable n @ 21..=100 => { println!("found him: {}", n); } // obligatory default match _ => { println!("too far gone"); } }
This seems a lot like math notation (function add defined over i32 * i32 with values in i32, f(x,y)=x+y;
fn add(x: i32, y: i32) -> i32 { return x + y; }
x+yfn main() { let a = 5; let x = { let a = 10; let b = 20; a + b } // will print "a: 5 x: 30" // b no longer exists here println!("a: {} x: {}", a, x); }
Methods are functions associated with a type.
:: operatorlet s = String::from("cool string");. (dot) operatorlet n = s.len(); (length of string)
Macros in rust are like functions but they end with a !.
See also