Idiomatic string parmeter types: &str vs AsRef<str> vs Into<String>

There are two pattern here:

  • (4) is a generalization of (1), passing by reference
  • (3) is a generalization of (2), passing by value/move (i.e. passing ownership)

I'd suggest the exact opposite.
In the end, you need an owned string, so passing ownership is more flexible for the caller.

With (1) and (4), you always go through a reference. This means, that you will always have to allocate a new String.

With (2) and (3) however, the caller knows that you will take ownership and can pass you any owned String. It's often the case that the caller has a temporary String lying around anyway that can just be moved.

My personal rules are:

  • If the function always takes ownership, pass by value.
  • If the function never takes ownership, pass by reference.
  • If the function sometimes takes ownership and sometimes not, use a Cow.
24 Likes