Asked ChatGPT to make a cheatsheet for me earlier.
### Variables and Data Types:
```rust
// Variable declaration
let variable_name: data_type = value;
// Immutable variable
let x: i32 = 10;
// Mutable variable
let mut y: f64 = 3.14;
// Constants (immutable)
const PI: f64 = 3.14159265359;
// Basic data types
let number: i32 = 42;
let float_number: f64 = 3.14;
let character: char = 'a';
let is_true: bool = true;
let text: &str = "Hello, Rust!";
```
### Control Flow:
```rust
// If-else statement
if condition {
// code block
} else if another_condition {
// code block
} else {
// code block
}
// While loop
while condition {
// code block
}
// For loop (range-based)
for i in 0..5 {
// code block (i takes values 0 to 4)
}
// For loop (collection-based)
let numbers = vec![1, 2, 3];
for num in numbers {
// code block (num takes values 1, 2, 3)
}
// Match statement (pattern matching)
match value {
pattern1 => { /* code block */ },
pattern2 if condition => { /* code block */ },
_ => { /* default code block */ },
}
```
### Functions:
```rust
// Function with no return value
fn function_name(param1: data_type, param2: data_type) {
// code block
}
// Function with a return value
fn add_numbers(a: i32, b: i32) -> i32 {
// code block
a + b
}
// Function with a generic type
fn generic_function
// code block
}
```
### Ownership and Borrowing:
```rust
// Ownership (Move semantics)
let vector1 = vec![1, 2, 3];
let vector2 = vector1; // vector1 is moved to vector2, vector1 is no longer valid
// Borrowing (Reference)
let vector3 = vec![4, 5, 6];
let reference = &vector3; // Borrowing the reference of vector3
```
### Structs and Enums:
```rust
// Struct declaration
struct MyStruct {
field1: data_type1,
field2: data_type2,
}
// Enum declaration
enum MyEnum {
Variant1,
Variant2(data_type),
Variant3 { field: data_type },
}
```
### Traits and Implementations:
```rust
// Trait declaration
trait MyTrait {
fn method1(&self);
fn method2(&mut self) -> data_type;
}
// Implementing a trait for a struct
impl MyTrait for MyStruct {
fn method1(&self) {
// code block
}
fn method2(&mut self) -> data_type {
// code block
}
}
```
### Error Handling:
```rust
// Result enum for error handling
enum Result
Ok(T),
Err(E),
}
// Function returning a Result
fn divide(x: f64, y: f64) -> Result
if y == 0.0 {
return Err("Division by zero".to_string());
}
Ok(x / y)
}
// Handling Result with match
match divide(10.0, 2.0) {
Ok(result) => println!("Result: {}", result),
Err(error) => eprintln!("Error: {}", error),
}
```
### Modules and Visibility:
```rust
// Module declaration (in separate file mod.rs or module_name.rs)
mod module_name {
// code inside the module
}
// Making items public within a module
mod my_module {
pub fn public_function() {
// code block
}
pub struct PublicStruct {
// fields
}
}
```
