【问题标题】:The trait bound `String: From<&T>` is not satisfied when my T is bound with Into<String>当我的 T 与 Into<String> 绑定时,特征绑定 `String: From<&T>` 不满足
【发布时间】:2026-01-28 15:30:01
【问题描述】:

我有以下代码,

impl<T: Debug + Into<String> + Clone> TryFrom<Vec<T>> for Positionals {
  type Error = &'static str;
  fn try_from(mut vec: Vec<T>) -> Result<Self, Self::Error> {
    let mystr: String = vec.get(0).unwrap().into();

而该代码正在产生此错误,

error[E0277]: the trait bound `String: From<&T>` is not satisfied
  --> bin/seq.rs:21:43
   |
21 |         let mystr: String = vec.get(0).unwrap().into();
   |                                                 ^^^^ the trait `From<&T>` is not implemented for `String`
   |
   = note: required because of the requirements on the impl of `Into<String>` for `&T`
help: consider introducing a `where` bound, but there might be an alternative better way to express this requirement

我很困惑为什么这会产生错误,因为我在Vec&lt;T&gt; 上有一个特征绑定,因此T 必须实现Into&lt;String&gt;,还需要什么?我不明白这是为什么,我删除了into(),我明白了

let mystr: String = vec.get(0).unwrap();
           ------   ^^^^^^^^^^^^^^^^^^^ expected struct `String`, found `&T`

如何将Vec&lt;T&gt; 中的T 转至String?我之所以做Vec&lt;T&gt;而不是Vec&lt;String&gt;是因为我也想支持Vec&lt;&amp;str&gt;

【问题讨论】:

    标签: string rust type-conversion traits


    【解决方案1】:

    您的代码的问题在于您的向量为您提供了引用,即&amp;String。虽然 Into&lt;String&gt; 对于 String 的实现很简单,但对于 &amp;String 没有实现,这需要克隆。您可以实现编译器的建议并添加where T: From&lt;&amp;String&gt;,但它需要额外调整生命周期并且再次不支持&amp;str

    要同时支持&amp;strString,您可以使用AsRef&lt;str&gt;

    impl<T: Debug + Clone + AsRef<str>> TryFrom<Vec<T>> for Positionals {
        type Error = &'static str;
        fn try_from(mut vec: Vec<T>) -> Result<Self, Self::Error> {
            let mystr: String = vec[0].as_ref().into();
            todo!()
        }
    }
    

    通过以下两个编译:

    Positionals::try_from(vec!["foo",]);
    Positionals::try_from(vec!["foo".to_owned(),]);
    

    Playground

    旁注:您可以使用vec[0] 代替vec.get(0).unwrap()。 (为防止意外移出向量,只需添加借位,即&amp;vec[0]。)

    【讨论】:

    • 出于好奇,为什么 into 方法不起作用?为什么T支持Into&lt;String&gt;时会出现上述错误?
    • @EvanCarroll 因为Into&lt;String&gt; 是(简单地)为String 定义的,但是您有&amp;String 因为您指的是向量中的现有项目。 (我现在已经修改了答案以提及这一点。)