Created
May 8, 2018 20:26
-
-
Save attdona/52126d892a38f4c8d2593639c7579905 to your computer and use it in GitHub Desktop.
simple examples of passing values by reference and references by reference
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 Foo { | |
n: u32, | |
} | |
fn overwrite<T: Copy>(input: &mut T, new: &mut T) { | |
// FORBIDDEN: you will copy the pointer pointing to a future freed memory | |
// *input = *new; | |
} | |
fn main() { | |
let foo_long = Box::new(Foo { n: 1 }); | |
let mut foo_long_ref = &foo_long; | |
{ | |
let foo_short = Box::new(Foo { n: 2 }); | |
let mut foo_short_ref = &foo_short; | |
// The args are passed as References by Reference | |
overwrite(&mut foo_long_ref, &mut foo_short_ref); | |
} | |
println!("{:?}", foo_long_ref); | |
} |
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(Copy, Clone, Debug)] | |
struct Foo { | |
n: u32, | |
} | |
fn overwrite<T: Copy>(input: &mut T, new: &mut T) { | |
// you are copying bits, it is safe | |
*input = *new; | |
} | |
fn main() { | |
let mut foo_long = Foo { n: 1 }; | |
{ | |
let mut foo_short = Foo { n: 2 }; | |
// The args are passed as Values by Reference | |
overwrite(&mut foo_long, &mut foo_short); | |
} | |
println!("{:?}", foo_long); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment