Critic of function parameter and return value explanation

Am I correct in what I say is typical here?

Function parameters of non-scalar types such as structs typically have reference types. This is because usually the function wants to borrow their values rather than take ownership. If the caller uses a variable to pass a non-scalar value and the function takes ownership, the caller loses ownership and can no longer use the variable unless the function returns it.

Function return values of non-scalar types such as structs typically have non-reference types. This is because usually the function creates the value and wants to transfer ownership to the caller.If a function creates a non-scalar value and returns a reference to it, the code will not compile because the value goes out of scope and is dropped.

1 Like

Yes, I think you are basically correct, except that when you say "non-scalar", you should say "non-copy". In rust, you can decide when you create a type if is "copyable".


struct SmallCoord {
    x: u8,
    y: u8,

This SmallCoord is not a scalar type, but since it is Copy, you can pass it by value without loosing ownership (and since its a quarter of the size of a pointer, it is more efficient to pass it by value than by reference).


Your first paragraph is essentially correct, but I'd usually talk about it in terms of the Copy trait instead of scalar/non-scalar values-- That's the marker that the compiler actually uses to determine behavior. The scalar values all implement it but structs can, too, if the fields are all Copy and the programmer requests it. For the second paragraph, everything you wrote is applicable to all types, so the "non-scalar" qualifier can potentially be confusing.

Depending on what this text is for, you might want to spend a sentence or two on why you might choose the atypical case for each of these:

  • Taking ownership of a parameter means that you now get to decide when and how the value is destroyed.
  • Returning a reference can be more efficient, but must refer to a value owned by one of the borrowed parameters; they're the only things available that could own it.

There are also more exotic pointer types that blur the conceptual line between reference and ownership like Arc, Rc, and Cow. Acknowledging their existence might be appropriate.


In addition to what others have said, I'd like to plug the actual documentation for the Copy trait, which was very helpful for me in grasping what it means/does:

And also this post by @trentj in an old thread:


Quick point out that often the size is more than the basic size_of.

Rust also has bound types.

In the case of taking a &mut parameter and returning a bound type. The caller now owns the returned and the lifetime can prevent use of the original variable.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.