Skip to content

Instantly share code, notes, and snippets.

@attdona
Created May 8, 2018 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attdona/52126d892a38f4c8d2593639c7579905 to your computer and use it in GitHub Desktop.
Save attdona/52126d892a38f4c8d2593639c7579905 to your computer and use it in GitHub Desktop.
simple examples of passing values by reference and references by reference
#[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);
}
#[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