Pass by reference or move ownership by default

When to default passing by reference or taking ownership when passing structs to functions that I need to only read only?

An example would be if I am creating a repository to take a struct model to use the fields to create some query. I am unsure at the time of writing the repository if potential callers would need to use the struct after passing the reference.

I would think that passing by reference would be best to have flexibility if a struct ended up needing to be used later, but unsure if its bad practice to pass everything by reference as default or if it is better to give ownership by default.

If you can do what you need to do by reference (without unconditionally needing some significant clones, etc), you would typically take a reference, except for small Copy types like primitive numbers.

Losing ownership of something can be a pain to the caller. Having something go out of scope later instead of being dropped sooner (via giving away ownership) is usually not.

Ownership based builder patterns may be considered an exception.

5 Likes