Moves in Function Calls
When you pass a value to a function, the value is assigned to the function parameter. This transfers ownership:
1. fn say_hello(name: String) {
2. println!("Hello {name}")
3. }
5. fn main() {
6. let name = String::from("Alice");
7. say_hello(name);
8. // say_hello(name);
9. }
- With the first call to
say_hello,maingives up ownership ofname. Afterwards,namecannot be used anymore withinmain. - The heap memory allocated for
namewill be freed at the end of thesay_hellofunction. maincan retain ownership if it passesnameas a reference (&name) and ifsay_helloaccepts a reference as a parameter.- Alternatively,
maincan pass a clone ofnamein the first call (name.clone()). - Rust makes it harder than C++ to inadvertently create copies by making move semantics the default, and by forcing programmers to make clones explicit.
