Generic function accepting &str or moving String without copying
Asked Answered
U

1

11

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.

Underpin answered 6/8, 2017 at 19:30 Comment(0)
I
16

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"));
}
Intersexual answered 6/8, 2017 at 19:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.