Daily Learnings: Mon, Sep 25, 2023
We love life, not because we are used to living but because we are used to loving. — Friedrich Nietzsche
Rust: Copy vs. Move
More notes from the Rust Programming Language Full Course, offered by freeCodeCamp.
- In the Rust programming language, scalar types with fixed sizes (primitive types like the various number types, characters, etc…) are copied, whereas dynamically-sized data won’t be copied
- Heap-stored data is potentially expensive to copy
- Instead, pointers to that data are copied, and the original pointer is discarded
- If both pointers continued to live on, it would violate the second rule: data can only have 1 owner at a time
- Fixed-size data that is stored on the stack is cheap to copy
// i32, therefore these are both referenceable and the data is copied on the stack
let x = 5;
let y = x
// String, which is heap-stored. s1 would be dropped and not referenceable later
let s1 = String::from("Hello World!");
let s2 = s1;
s1 // ERROR!
// You can clone data on the heap, but you have to explicitly ask for it
let s1 = String::from("Hello World!");
let s2 = s1.clone();