Transferring Ownership to Functions
When you pass a variable to a function in Rust, you transfer ownership of that variable. Once ownership is transferred, the original variable is no longer accessible in its previous scope. For example, consider passing a string to a function:s is created in the main function and then moved into the takes_ownership function. Attempting to use s after the function call will trigger a compile-time error because its ownership has been transferred.
Working with Types that Implement the Copy Trait
Rust’s primitive types, like integers, implement theCopy trait. When an integer is passed to a function, Rust creates a copy instead of moving it, meaning that the original variable remains valid after the function call.
For example:
x is passed to makes_copy, a copy is made, and the original variable x remains intact for use in subsequent code.
Returning Ownership from Functions
Functions can also transfer ownership back to the caller. This is useful when you create or modify values within a function and need the modified value outside its scope. Consider the following example where one function gives ownership of a string and another function takes a string and returns it:Functions returning ownership provide flexibility when modifying data. Keep in mind that once a variable’s ownership is transferred, it cannot be used in its original form unless returned.
Modifying a String by Transferring Ownership
A function can accept a value by taking ownership, modify it, and then return it. This is a common pattern for functions that need to transform input data without borrowing it. For example, consider a function that appends text to a string:s is passed to modify_string. After appending additional text, the modified string is returned and printed in the main function.
Copying and Returning Primitive Types
Since primitives like integers implement theCopy trait, passing these values to and returning them from functions involves copying rather than moving. This ensures that original values remain unchanged and accessible.
For example:
Through these examples, we have explored how Rust’s ownership model interacts with functions:
- Variables can have their ownership transferred to functions, rendering them inaccessible in their original scope.
- Primitive types implementing the
Copytrait are duplicated rather than moved, allowing them to remain available. - Functions can return ownership, making it simpler to modify data within functions and then pass it back.