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.
Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.
The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.
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"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With