Last active
October 30, 2022 15:35
-
-
Save Clivern/c4980186eccd392e8e39477439244d04 to your computer and use it in GitHub Desktop.
Understanding Ownership
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let x: i32 = 2; | |
take_ownership_x(x); | |
println!("x = {}", x); | |
let y = String::from("Hello"); | |
take_ownership(y); | |
// the following line shall fail since value borrowed above | |
// println!("y = {}", y); | |
let o = String::from("Hello"); | |
println!("o len = {}", get_len(&o)); | |
println!("o = {}", o); | |
let z = String::from("Hello"); | |
take_ownership(z.clone()); | |
println!("z = {}", z); | |
// Mutable References | |
let mut g = String::from("Hello"); | |
g = take_ownership_and_give(g); | |
println!("g = {}", g); | |
// Mutable References | |
let mut k = String::from("Hello"); | |
take_ownership_and_update(&mut k); | |
println!("k = {}", k); | |
} | |
fn take_ownership_x(x: i32) { | |
println!("x = {}", x) | |
} | |
fn take_ownership(y: String) { | |
println!("y = {}", y) | |
} | |
fn take_ownership_and_give(mut y: String) -> String { | |
y.push_str(" World"); | |
y | |
} | |
fn take_ownership_and_update(y: &mut String) { | |
y.push_str(" World") | |
} | |
fn get_len(y: &String) -> usize { | |
y.len() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reference https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html#understanding-ownership