diff --git a/ownership/README.md b/ownership/README.md index c8f2fa5..b245433 100644 --- a/ownership/README.md +++ b/ownership/README.md @@ -9,9 +9,41 @@ which cleans up data in memory on a regular basis. Rust does neither. It uses `Ownership` to manage memory and data, so each piece of data has an owner, and when that owner gets out of scope, the value is dropped. ## 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. ## Variable Scope +the scope of a variable is like this + +```rust +{ // here `s` is out of scope, not declared yet + let s = "text"; // here `s` is in scope + + // we can do stuff with `s` here ... +} // now `s` is out of scope +``` + +so when `S` comes into scope, it is valid. +It remains valid until it is out of scope. + + +## The String Type +So far we have talked about data types that are of known length, and are stored in the stack. Now we'll focus on data types that can grow, and are allocated to the heap. This example will use the `String` type. +`String` is of an unknown length at compile time. + +So consider this example +```rust +let mut s = String::from("Hello"); + +s.push_str(", world!"); // appends a literal to a string + +println!("{s}"); // prints out "Hello, world!" +``` + +## Memory and Allocation +A string literal, we know the value at compile time, so the value will be hard coded into the binary. Therefore, string literals are fast and efficient. +With the `String` we must allocate an amount of memory on the heap, which by its very nature is unknown at compile time. that means that +- memory must be requested by the memory allocator at runtime +- We need a way to returning this memory to the allocator when we're done with our `String` +When the `String` function is once again out of scope, i.e. the curly braces it is in are moved on, then Rust calls a special `drop` function to clean up the memory.