Ownership Exception in Function Arguments

ยท

2 min read

When I began my journey in learning Rust ownership, enough emphasis wasn't made on the exceptions. In this article, we would discuss the limitation of ownership regarding function inputs (also referred to as function arguments).

fn print() {
    let numbers = [1,2,3,4,5, 2];
    output(numbers); // LINE 3
    output(numbers); // LINE 4
}

fn output (numbers: [u8; 6]){
    for n in numbers.iter() {
        println!("{n}");
    }
}

Originally, you would have expected print to fail on the second call to output on line 4.

If you were surprised this code ran successfully without an error, it means you too do not know about the exceptions. So let's talk about it.

The Default Behaviour of Function Arguments

The default behavior is for a function to take input by value and hence ownership of the variable is moved into the function. For example, we would have expected numbers to move to the output function after line 3.

Why Not?

The answer that stood closest would have been because the argument type resides on the stack and not the heap. Well, this is somewhat correct.

The actual exception to this rule is if the type implements a special trait called Copy, the function would call this on the input (or arguments) therefore the caller still maintains ownership of the variable. If the Copy trait doesn't exist on any of the input, the function would then take ownership of them.

Now you know why the code earlier mentioned worked ๐Ÿ˜.


Types that automatically implement the Copy trait are

  • primitive/scalar types

  • Tuples

  • Arrays, and

  • References

fn print() {
    // THIS IS NOW A VECTOR ๐Ÿ‘€
    let numbers = vec![1,2,3,4,5,12];
    output(numbers); // LINE 3
    output(numbers); // LINE 4
}

fn output (numbers: [u8; 6]){
    for n in numbers {
        println!("{n}");
    }
}

Since the Vec type ( an in numbers) doesn't implement the Copy trait, Line 4 would fail and the code crash.

However, Please note that if a type contains any non-Copy fields, the Copy trait will be silenced.

Thanks for reading thus far, subscribe to continually get short and useful Rust content like this. Happy hacking ๐ŸŽ‰.

ย