Last active
April 19, 2021 20:32
-
-
Save kahunacohen/07bb5f7b4ff7497440afbf24d21b67bd to your computer and use it in GitHub Desktop.
This file contains 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
#[derive(Debug)] | |
struct Person { | |
name: String | |
} | |
#[derive(Copy,Clone,Debug)] | |
struct CopyablePerson<'a> { | |
name: &'a str | |
} | |
fn main() { | |
// This is OK because ints are copyable, | |
// they don't need to be moved because they always point to | |
// the stack. | |
let x = 1; | |
println!("{}", add_one(x)); | |
println!("{}", x); | |
let y = x; | |
println!("{}", y); | |
println!("{}", x); | |
// // Here, we can't re-assign cause a struct is in the heap. | |
let name = String::from("Peter"); | |
let p = Person{name}; | |
println!("{:?}", p); | |
println!("{}", get_name(p)); | |
// But if we properly derive the copy trait we can... | |
let p2 = CopyablePerson{name: "Peter"}; | |
let p3 = p2; | |
println!("{:?}", p3); | |
} | |
fn add_one(x: u8) -> u8 { | |
x +1 | |
} | |
fn get_name(person: Person) -> String { | |
p.name | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment