Generic function accepting &str or moving String without copying

Viewed 1267

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.

1 Answers
Related