Ownership and Functions
Ownership and Functions
the assignment of a variable to another variable will copy or move it. In case of passing variables to the functions, similar can happen.
When a variable whose memory is allocated on heap goes out of scope, the value will be cleaned up by drop unless the data has been moved such that it is now being owned by another variable.
Passing Values to a Function
- The ownership of the variable is
- Copied if the value is a primitive data type so the variable can be reused after the function call
- Moved if the value is a non-primitive data type so the value becomes inaccessible after the function call
output
In this example, value str of type String is moved when passed to the function as an argument and my_int
of type i32
is copied.
Return Values from a Function
Returning values from a function transfer the ownership to the caller function.
output
Here, in this example, variable str_1
gains the ownership of a String when the value is
returned from the function move_return_value_str_1
. Variable str_2
is declared and its value is passed to the
function moves_str_2_return_str_2
. Upon being returned from the function the value is saved in str_3
.
Note:str_2
becomes inaccessible since its value is moved in the function
Last updated a year ago.