Accepting the common function & str or moving a String without copying

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

The internal function requires String , so I would also like to avoid unnecessary redistribution if the caller calls the function using String .

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

For accepting links, I know that I can use foo<S: AsRef<str>>(s: S) , but what about a different path?

I think a general argument based on ToOwned might work (works for &str , and I assume it is no-op on String ), but I cannot figure out the exact syntax.

+8
generics ownership-semantics rust
source share
1 answer

I think you can achieve with Into trait , for example:

 fn foo<S: Into<String>>(s: S) -> String { return s.into(); } fn main () { foo("borrowed"); foo(format!("owned")); } 
+10
source share

All Articles