MaiaVictor
MaiaVictor

Reputation: 52957

When should I use a reference instead of transferring ownership?

From the Rust book's chapter on ownership, non-copyable values can be passed to functions by either transferring ownership or by using a mutable or immutable reference. When you transfer ownership of a value, it can't be used in the original function anymore: you must return it back if you want to. When you pass a reference, you borrow the value and can still use it.

I come from languages where values are immutable by default (Haskell, Idris and the like). As such, I'd probably never think about using references at all. Having the same value in two places looks dangerous (or, at least, awkward) to me. Since references are a feature, there must be a reason to use them.

Are there situations I should force myself to use references? What are those situations and why are they beneficial? Or are they just for convenience and defaulting to passing ownership is fine?

Upvotes: 28

Views: 8326

Answers (1)

Peter Hall
Peter Hall

Reputation: 58715

Mutable references in particular look very dangerous.

They are not dangerous, because the Rust compiler will not let you do anything dangerous. If you have a &mut reference to a value then you cannot simultaneously have any other references to it.

In general you should pass references around. This saves copying memory and should be the default thing you do, unless you have a good reason to do otherwise.

Some good reasons to transfer ownership instead:

  1. When the value's type is small in size, such as bool, u32, etc. It's often better performance to move/copy these values to avoid a level of indirection. Usually these values implement Copy, and actually the compiler may make this optimisation for you automatically. Something it's free to do because of a strong type system and immutability by default!
  2. When the value's current owner is going to go out of scope, you may want to move the value somewhere else to keep it alive.

Upvotes: 24

Related Questions