ownership completed
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
pub fn run() {
|
||||
println!("\n=== Ownership ===\n");
|
||||
|
||||
// The stack and the heap
|
||||
// So ownership is a set of rules that govern how Rust managages memory
|
||||
// arrays and simple variables are allocated to the stack. These have fixed and known lentghs at
|
||||
// compile time. This is fast on the stack.
|
||||
// However, when working with data of unknown lengths, for example String::new(), Rust cannot
|
||||
// know the length at compile time. This is then allocated to the heap with a reference in memory.
|
||||
|
||||
// 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 is dropped.
|
||||
|
||||
// VARIABLE SCOPE
|
||||
|
||||
// This is a string literal. This is hardcoded into the program at compile time.
|
||||
|
||||
{ // s is not valid here, since it has not been declared
|
||||
let s = "hello"; // s is valid from this point onward
|
||||
println!("{s}");
|
||||
// Do stuff with s
|
||||
|
||||
} // this scope is now over, and the variable s is no longer valid
|
||||
// when s comes into scope, it is valid
|
||||
// when s goes out of scope, it is invalid
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user