How do u decide if a function should accept &param or param

When is it right to create a function to move a value and when not? What is your default choice?

Here I was forced to make sign() accept a reference instead of moving it because i have to mutate the vector afterwards.

let mut params = params.into().unwrap_or(vec![]);
let signature = dbg!(self.sign(&params));
params.push(("signature", signature));

There may be a proper description or idiomatic way to do details elsewhere.

But my thought process is the following:

  • If a function just needs to read state temporarily, or it's acceptable to clone the value, then a reference is ideal.
  • If a function needs to modify something, without actually just taking it as a whole (example an iterator or writer), then a mutable reference is ideal.
  • If a function actually ends up consuming and then keeping track of the object totally, then letting it own it is ideal.

I just make everything a reference, unless I get an error personally.

1 Like

You could also see the justification from the idiomatic rust book.

Use borrowed types for arguments - Rust Design Patterns

Just param will eliminate the param, and & will preserve it. So the solution is based if you want to continue to use the param after the function call, or okay with discarding it.

2 Likes