Here are the basics I covered:
Basics
- Variable Declaration:
let var_name = value;
- Immutable Binding:
let x = 5;
- Mutable Binding:
let mut y = 10;
- Constants:
const MAX_POINTS: u32 = 100_000;
- Printing:
println!("Hello, world!");
Data Types
- Integer:
i32
,u32
,i64
,u64
- Floating Point:
f32
,f64
- Boolean:
bool
- Character:
char
- Tuple:
(i32, f64, u8)
- Array:
[i32; 5]
(fixed size) - Slice:
&[i32]
(reference to a contiguous sequence)
Control Flow
- if expression:
if condition { } else { }
- loop:
loop { }
- while loop:
while condition { }
- for loop:
for item in iterable { }
- match:
match value { pattern => { /* code */ } }
Functions
- Declaration:
fn function_name(param: Type) -> ReturnType { }
- Calling:
function_name(arg)
Ownership
- Ownership Rules: Each value in Rust has a variable that’s called its owner.
- Borrowing:
&
(immutable) and&mut
(mutable) - Lifetimes: Ensures that borrowed references are valid.
Error Handling
- Result:
Result<T, E>
for functions that might fail. - panic!: Macro to cause the program to crash and display a message.
Structs
- Declaration:
struct MyStruct { field1: Type, field2: Type }
- Instance:
let instance = MyStruct { field1: value1, field2: value2 };
Enums
- Declaration:
enum MyEnum { Variant1, Variant2 }
- Instance:
let instance = MyEnum::Variant1;
Traits
- Declaration:
trait MyTrait { /* methods */ }
- Implementing:
impl MyTrait for Type { /* method implementations */ }
Modules
- Declaration:
mod module_name { /* module contents */ }
- Using:
use module_name::item_name;
Unsafe Rust
- Unsafe Block:
unsafe { /* unsafe code */ }
Useful Tools
- Cargo: Rust’s package manager and build system.
- Rustfmt: Code formatter.
- Clippy: Linter for Rust code.