Daily Learnings: Mon, Oct 02, 2023
Until you make peace with who you are, you’ll never be content with what you have. — Doris Mortman
Learnings about Rust: Move & Copy with Functions & Scope
More notes from the freeCodeCamp Rust Programming Language course
- In my notes about Move & Copy from Sept 25, we learned a bit about how the variable’s underlying memory store (heap vs. stack) influences how it’s moved vs. copied in the context of same-scope variable declaration
- Multi-Function scope also is affected by move vs. copy variables:
fn main() {
let str = String::from("Hello World"); // str comes into scope and is usable
takes_ownership(str); // str's value is **_moved_** into another function's ownership
// str can't be used here anymore without an error happening
let x = 5 // x is of type i32
makes_copy(x); // i32 is Copy-based, meaning that its value is copied into
// the makes_copy() function scope, and x is still accessible
// here in this scope after
let s1 = gives_ownership(); // This function gives up its ownership of its return value
// to the main() function
let s2 = String::from("Hi!");
let s3 = takes_and_gives(s2); // s2 is moved into this function and no longer accessible
// in the main() function.
}
// At the end of main():
// - s3 goes out of scope and is dropped
// - s2 was moved, therefore it was already droppped
// - s1 goes out of scope and is dropped
// - x goes out of scope and is dropped
// - str was moved, therefore it was already dropped
fn takes_ownership(some_string: String) {
println!("{}", some_string);
// Here some_string goes out of scope, and `drop` is called.
// Backing memory is freed
}
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
// Here some_integer goes out of scope, and nothing special happens
}
fn gives_ownership() -> String {
let some_string = String::from("Hello Universe!");
some_string // some_string is returned and moves out to the
// calling function
}
fn takes_and_gives(some_string: String) -> String {
some_string
}