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?
In Rust, by contrast, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does.
Rust supports mutable references which means we can change the value it references if it's a mutable variable. There are some restrictions on how we use mutable references. If the immutable reference exists in our program then We can't have a mutable reference into the same value.
A mutable type is a type whose instance data can be modified. The System. Text. StringBuilder class is an example of a mutable reference type. It contains members that can change the value of an instance of the class.
Rust allows you to pass a reference to the variable instead. This allows the parent function to keep the scope of the original variable whilst allowing a child function to use it. The clear difference in the code is the use of “&” when passing the variable to the function and in the function definition.
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:
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!If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With