-
Notifications
You must be signed in to change notification settings - Fork 0
Deciding on Argument Types
With every function we write in Rust, we need to think about whether we are receiving values or refs!
With every data structure we define, we need to think about whether we are storing values or refs!
Add an account to the list of accounts.
Method
add_account()
So the question for this one is, is it going to be an account value? account:Account
, is it going to be a reference to an account? account: &Account
, or is it going to be a mutable reference to an account: account: &mut Account
. All three could be potentially viable depending upon what we are trying to achieve inside this function.
To indicate whether we are taking ownership, read-only or mutable ref depends on the type signature.
Here is the general rule of thumb, but it will not always solve our problems, but will generally lead us down the right path:
- Need to store the argument somewhere? -> Favor taking ownership (receive a value)
- Need to do a calculation with the value? -> Favor receiving a read-only ref
- Need to change the value in some way? -> Favor receiving a mutable ref
We might see cases where we need to store something but we might need a reference or mutable reference, but in this case we are trying to add an account to a list of accounts, so that sounds to me like storage, we are storing some kind of value here. So almost definitely we are falling into the first case, so receive ownership of accounts to store it inside a vector of accounts, so account: Account
.