9

I want to write a generic function that accepts any kind of string (&str/String) for convenience of the caller.

The function internally needs a String, so I'd also like to avoid needless re-allocation if the caller calls the function with String.

foo("borrowed");
foo(format!("owned"));

For accepting references I know I can use foo<S: AsRef<str>>(s: S), but what about the other way?

I think generic argument based on ToOwned might work (works for &str, and I'm assuming it's a no-op on String), but I can't figure out the exact syntax.

Kornel
  • 97,764
  • 37
  • 219
  • 309

1 Answers1

13

I think what you are after can be achieved with the Into trait, like this:

fn foo<S: Into<String>>(s: S) -> String {
    return s.into();
}

fn main () {
    foo("borrowed");
    foo(format!("owned"));
}
Florian Weimer
  • 32,022
  • 3
  • 48
  • 92