Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function accepting &str or moving String without copying

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.

like image 453
Kornel Avatar asked Aug 06 '17 19:08

Kornel


People also ask

What is meant by generic function?

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.

What is generic type argument?

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.

What is the syntax for generic function?

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.


1 Answers

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"));
}
like image 143
Florian Weimer Avatar answered Sep 22 '22 05:09

Florian Weimer