Skip to content

Deciding on Argument Types

Daniel Cortes edited this page Aug 22, 2024 · 4 revisions

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!

Bank

Add an account to the list of accounts.

Method or Assoc Func?

Method

Name

add_account()

Args

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:

Function Argument Types

  • 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.