【问题标题】:Generic function accepting &str or moving String without copying接受 &str 或移动字符串而不复制的通用函数
【发布时间】:2018-01-14 02:31:30
【问题描述】:

为了方便调用者,我想编写一个接受任何类型字符串 (&str/String) 的通用函数。

函数内部需要String,所以如果调用者使用String 调用函数,我还想避免不必要的重新分配。

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

我知道我可以使用foo<S: AsRef<str>>(s: S) 来接受引用,但是其他方式呢?

我认为基于 ToOwned 的通用参数可能有效(适用于 &str,我假设它对 String 无效),但我无法弄清楚确切的语法。

【问题讨论】:

    标签: generics rust ownership-semantics


    【解决方案1】:

    我认为您所追求的可以通过Into trait 实现,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 2013-05-05
      • 2021-08-03
      • 1970-01-01
      相关资源
      最近更新 更多