Skip to content

Instantly share code, notes, and snippets.

@peerhenry
Created January 1, 2019 01:31
Show Gist options
  • Select an option

  • Save peerhenry/c204d36cdae48701eda20fc1648a4711 to your computer and use it in GitHub Desktop.

Select an option

Save peerhenry/c204d36cdae48701eda20fc1648a4711 to your computer and use it in GitHub Desktop.
Taking ownership: copy versus move.
/*
This program outputs:
Bonjour 5
Hello 5
Bonjour 7
Bonjour 11
Hello 11
*/
fn main() {
// Scenario 1: taking ownership of a primitive type
let bar = Bar{ value: 5 };
take_u32(bar.value);
println!("Hello {}", bar.value); // legal: value was copied
// Scenario 2: taking ownership of a struct instance
let foo = Foo {
bar: Bar { value: 7 }
};
take_bar(foo.bar);
// println!("Hello {}", foo.bar.value); // illegal: bar was moved
// Scenario 3: taking ownership of a copyable struct instance
let other_foo = OtherFoo {
bar: CopyableBar { value: 11 }
};
take_copyable_bar(other_foo.bar);
println!("Hello {}", other_foo.bar.value); // legal: bar was copied
}
// the following functions take ownerships
fn take_u32(number: u32) {
println!("Bonjour {}", number);
}
fn take_bar(bar: Bar) {
println!("Bonjour {}", bar.value);
}
fn take_copyable_bar(bar: CopyableBar) {
println!("Bonjour {}", bar.value);
}
// the structs used for this example
struct Bar {
value: u32
}
struct Foo {
bar: Bar
}
#[derive(Copy, Clone)]
struct CopyableBar {
value: u32
}
struct OtherFoo {
bar: CopyableBar
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment