【问题标题】:Trait is not implemented for the type `&str` [E0277]`&str` 类型没有实现特征 [E0277]
【发布时间】:2016-01-28 15:04:14
【问题描述】:

我有一个 str 的 trait 定义,我定义了一个带有 &self 的函数。如果我在静态 &str 上从 main 调用这个函数,一切都很好。如果我从采用特征对象参数的函数中调用相同的函数,则会收到以下错误:MyTrait is not implemented for the type&str[E0277]

最后我有一个解决方法,但我不清楚成本,我是在复制字符串吗?

#[derive(Debug)]
struct Thingie{
 pub name: String, // rather than &a str for Thingie<'a>
}

trait MyTrait{
    fn to_thingie(&self)->Option<Thingie>;
}

impl MyTrait for str{
    fn to_thingie(&self)->Option<Thingie>{
        println!(">>MyTrait for str");
        Some(Thingie{name:self.to_string()})
    }
}


fn method_on_trait <T:MyTrait> (thing:T){
   let v= thing.to_thingie();
   println!("Method on trait: {:?}",v);
}

fn main(){
 println!("in main: {:?}","test".to_thingie());
 method_on_trait("test");
}

//TODO: Uncomment this for a fix. WHY?
//Is this creating a copy of the string or just transfering the binding?
// impl<'a> MyTrait for &'a str{
//     fn to_thingie(&self)->Option<Thingie>{
//         println!(">>MyTrait<'a> for &'a str");
//         (*self).to_thingie()
//     }
// }

【问题讨论】:

标签: rust traits


【解决方案1】:

您需要告诉method_on_trait,它可以处理未调整大小的类型,并将对 T 的引用传递给它(不是直接 T,此时可能没有调整大小并且不能按值传递)。 第一个您可以将?Sized“绑定”添加到T,第二个通过将thing 设为&amp;T

fn method_on_trait<T: MyTrait + ?Sized> (thing: &T) {
   let v = thing.to_thingie();
   println!("Method on trait: {:?}",v);
}

这里发生了什么,MyTrait 只为str 实现,这是一个未调整大小的类型。您尝试在 main 中将“测试”(这是一个 &amp;'static str)传递给 method_on_trait,这会导致 E0277 错误。

您的注释代码正在为&amp;str 实现MyTrait,这会使您的原始代码编译,因为您确实将&amp;str 传递给method_on_trait。没有复制原字符串,&amp;str基本上只是a pointer to it plus a length info

【讨论】:

  • 谢谢,我完全忘记了 ?Sized 特征。
  • 感谢@Pablo 非常清晰详细的解释。这很有帮助。
猜你喜欢
  • 1970-01-01
  • 2019-12-08
  • 2015-11-11
  • 2015-07-15
  • 2016-05-19
  • 2015-10-08
  • 1970-01-01
  • 2021-07-18
  • 2014-09-01
相关资源
最近更新 更多