为了方便调用者,我想编写一个接受任何类型字符串 ( &str
/String
) 的通用函数。
函数内部需要一个 String
,所以如果调用者使用 String
调用函数,我也想避免不必要的重新分配。 .
foo("borrowed");
foo(format!("owned"));
为了接受引用,我知道我可以使用 foo<S: AsRef<str>>(s: S)
, 但换一种方式呢?
我认为通用参数基于 ToOwned
可能有效(适用于 &str
,我假设它在 String
上是空操作),但我无法弄清楚确切的语法。
最佳答案
我认为您所追求的可以通过 Into
trait 实现,像这样:
fn foo<S: Into<String>>(s: S) -> String {
return s.into();
}
fn main () {
foo("borrowed");
foo(format!("owned"));
}
关于generics - 通用函数接受 &str 或移动字符串而不复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535820/