Skip to content

Instantly share code, notes, and snippets.

@Clivern
Last active October 30, 2022 15:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Clivern/c4980186eccd392e8e39477439244d04 to your computer and use it in GitHub Desktop.
Save Clivern/c4980186eccd392e8e39477439244d04 to your computer and use it in GitHub Desktop.
Understanding Ownership
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