owned this note
owned this note
Published
Linked with GitHub
# Rust Sessions
#### Why Rust
- Built-in multi-threading system
- Type-system - uncover bugs at compile time
- module system that simplifies code separation
- Robust tooling for docs generation, code linting and code auto formatting
- In summary, Rust maintains a significant balance between speed, safety, concurrency and portability
- Compilation to machine code is pretty fast
- Uses ownership for memory management
Primitive/Scalar Data Types
- Bool
- Float
- Integers
#### Data types:
- Memory only stores binary data - anything can be represented in binary
- Generally, programs determine what binary represents
-
- Primitives:
- boolean - true || false
- floating point - 2.5, 0.7
- char - '7'
- integers:
- signed (i)
- unsigned (u)
- strings - "gm"
# Rust Notes
#### 04-02-24
In Rust, both String and str are related to handling text, but they have different meanings and use cases.
`String`: This is a heap-allocated, growable, UTF-8 encoded string type. It is part of the standard library and is owned, meaning it has ownership semantics and can be mutable. You can manipulate it dynamically, and it is suitable for situations where you need to modify or grow the string at runtime.
Example
```rs=
let my_string = String::from("Hello, ");
let other_string = String::from("world!");
let combined_string = my_string + &other_string;
println!("{}", combined_string);
```
In this example, `String::from` creates a new String, and the + operator is used to concatenate two strings, taking ownership of the first one.
`str`: This is a string slice, which is an immutable view into a string. It is a reference to a sequence of UTF-8 bytes and is often used when you want to work with strings without taking ownership. str is a primitive type in Rust and is often seen as the borrowed form of a string. Example:
`let my_str: &str = "Hello, world!";`
In this example, `my_str` is a reference to a string slice.
In summary, String is a heap-allocated, growable, owned string type, while str is an immutable reference to a sequence of UTF-8 bytes. String is more flexible for dynamic string manipulation, while str is commonly used when you want to work with string data without taking ownership.
#### Why `&` in string
```rust=
let my_string = String::from("Hello, ");
let other_string = String::from("world!");
let combined_string = my_string + &other_string;
println!("{}", combined_string);
```
The `&` in `&other_string` is used to take a reference to `other_string` rather than taking ownership of it. The + operator in Rust is implemented to take ownership of its operands. However, the & before other_string creates a reference to it, allowing the + operator to borrow the content of other_string without taking ownership.
If you were to omit the &, the ownership of `other_string` would be transferred to `my_string`, and you wouldn't be able to use `other_string` afterward:
```rust=
let my_string = String::from("Hello, ");
let other_string = String::from("world!");
let combined_string = my_string + other_string; // Error: value moved
println!("{}", combined_string);
// other_string is now inaccessible because its ownership was transferred to combined_string
```
``` rs=
fn main() {
let owned_string = String::from("Hello, world!"); // Creates an owned String
let moved_string = transfer_ownership(owned_string);
// owned_string is no longer accessible here because its ownership was moved
println!("{}", moved_string);
}
fn transfer_ownership(s: String) -> String {
println!("Ownership transferred: {}", s);
s // Return ownership
}
```
#### Hey! Why not add `&` to `my_string`?
In Rust, the + operator for string concatenation expects the left operand to be a String and the right operand to be a &str. The & is automatically added to the String on the right side of the + operator by the Rust compiler through a mechanism called "Deref coercion" and "Borrow coercion."
`let combined_string = my_string + &other_string;`
The `&other_string` is automatically converted to a &str reference to its content, and the + operator is then able to concatenate a String with a `&str`. This is a convenient and ergonomic feature of Rust.
If you were to explicitly add & to my_string, it would result in a type error, because the + operator requires a String on the left side:
```rust=
let combined_string = &my_string + &other_string; // Error: mismatched types
```
So, the compiler automatically handles the borrowing and coercion for you in this specific context.
#### What is the difference between the above concatenation approach with using format macro to concat?
Using the + operator for string concatenation and the format! macro are two different approaches to building strings in Rust. Here are the key differences:
Ownership and Mutation:
+ Operator: It takes ownership of its operands. If you concatenate two String instances using +, the ownership of the left operand is transferred to the result, and the left operand cannot be used afterward unless it is cloned.
format! Macro: It creates a new String without taking ownership of its arguments. The original values are not modified or moved.
Flexibility:
+ Operator: It's more concise and can be convenient for simple concatenation operations. However, it can be less flexible for complex formatting tasks or when working with different types.
format! Macro: It provides more flexibility and control over the formatting of strings. You can include various types, expressions, and format specifiers within the macro, making it suitable for more complex string building.
Here's an example to illustrate the differences:
Using + operator:
```rust=
let name = String::from("John");
let greeting = "Hello, " + &name;
// ownership of name transferred to greeting
// name is no longer valid here
```
Using format! macro:
```rust=
let name = String::from("John");
let greeting = format!("Hello, {}", name);
// name is still valid here, as format! does not take ownership
```
In general, if you need simple concatenation and are comfortable with ownership transfer, the + operator might be more concise. If you require more complex formatting or want to keep ownership of the original values, the format! macro is often a more suitable choice.
Resources:
1. https://medium.com/israeli-tech-radar/rust-stack-and-heap-moves-and-copies-104b3146b977#:~:text=The%20stack%20and%20the%20heap%20in%20Rust&text=As%20such%2C%20they%20are%20abstractions,memory%20allocation%20size%20is%20unknown.
2. https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/the-stack-and-the-heap.html
# Understanding Ownership in Rust
- Ownership model is a way to manage memory
## WTF is Ownership
- Data structure/variable responsible for allocating and freeing the memory used to store value/data
## Ownership Rules
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
- https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
## WTF is Memory
- Component in a computer that stores data and instructions for the processor to execute
## 🚗 Manual vs. Automatic Cars — Memory Management Analogy
| Concept | Manual Car (C, C++) | Automatic Car (Rust) |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| **Gear Shifting** | You (the programmer) have full control and responsibility for shifting gears (allocating and freeing memory). | The car (compiler) shifts gears for you automatically (memory is managed via ownership, borrowing, and lifetimes). |
| **Stalling Risk** | High — if you forget to deallocate memory or free it twice, the program crashes (memory leaks, undefined behavior). | Low — Rust prevents stalls by enforcing rules at compile time (e.g., use-after-free, double free, data races are compile-time errors). |
| **Clutch Mastery (e.g., `malloc`/`free`)** | You need to master the clutch to drive smoothly. You call `malloc` and `free` and must get it *just right*. | No clutch to worry about — Rust handles memory cleanly and safely using its ownership system. |
| **Engine Control** | You have access to all internals — which is powerful but dangerous. | Rust still gives you access to internals (unsafe blocks), but wraps most behavior in safe abstractions. |
| **Driver Responsibility** | You're responsible for every aspect of memory. One small mistake, and the system misbehaves. | You're guided by the compiler to write safe and correct code. Mistakes are caught early, before runtime. |
| **Advanced Features** | Manual gives you more control and is better for fine-tuned performance. | Rust offers both: the ease of automatic with optional manual overrides (`unsafe`), without sacrificing performance. |
🧠 Memory-Specific Comparison
C/C++ (Manual Car):
You must manage when and how memory is allocated and freed.
Forgetting to free memory leads to leaks.
Freeing too early leads to dangling pointers.
Access from multiple threads leads to data races unless you're extra careful.
Rust (Automatic Car):
Memory is freed automatically when it goes out of scope — thanks to the ownership model.
You can’t access freed memory — the borrow checker stops you at compile time.
No garbage collector, but still automatic — performance remains close to C/C++.
Thread safety is baked into the type system — data races are compile-time errors.
🛠️ Bonus: C# as a Semi-Automatic Car
If you're bringing C# into the analogy:
Think of C# as a semi-automatic car.
You don’t have to manage memory directly (new allocates, GC cleans up).
But garbage collection can pause your app (GC pauses), and you don't control when it happens.
Rust gives you deterministic cleanup without a GC, like a car that knows exactly when to shift gears.
🎯 Key Takeaway
"Rust gives you the control of a manual with the safety and ease of an automatic — without ever stalling the engine."
This analogy helps students appreciate why Rust is safer than C/C++ and more predictable than garbage-collected languages like C# or Java, all while remaining close to the metal.
| Current Solutions for Managing Memory | Pros | Cons |
|----------|----------|----------|
| Garbage collection | <li>Error free</li><li>Faster write time</li> | <li>no control over memory</li><li>slower/unpredictable runtime performance</li> <li>larger program size</li> |
| Manual Memory Management | <li>control over memory</li><li>faster run time</li><li>smaller program size</li> |<li>Error prone</li><li>slower write time</li> |
| Ownership Model | <li>full control over memory</li><li>error free</li><li>faster run time</li><li>smaller program size</li> | <li>slower write time</li><li>steep learning curve</li>
- Deep dive into stack and heap - https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/the-stack-and-the-heap.html
### Bash Scripting
https://www.youtube.com/watch?v=tK9Oc6AEnR4