首页 > 解决方案 > 在特质 impl 中理解自我

问题描述

我对自己有点困惑。你能帮我吗?我试图将新值追加或推送到vec. 这仅表明我不知道自我实际上是什么。我得到的错误是:

---- ^^^^ this call modifies `self` in-place
   |         |
   |         you probably want to use this value after calling the method...
   = note: ...instead of the `()` output of method `push`

为什么以下工作但......

trait AppendBar {
    fn append_bar(self) -> Self;
}

impl AppendBar for String {
    fn append_bar(self) -> Self{
        self.to_string() + "Bar"
    }
}

这和...

impl AppendBar for Vec<String> {
    fn append_bar(self) -> Self{
        let mut bar = vec![String::from("Bar")];

        bar.push(self);

        bar
    }
}

这和...

impl AppendBar for Vec<String> {
    fn append_bar(self) -> Self{
        let bar_vec = vec!["Bar".to_string()];

        self.append(bar_vec)
    }
}

这不?

trait AppendBar<T> {
    fn append_bar(self) -> Self;
}

impl<T> AppendBar<T> for Vec<T> {
    fn append_bar(self) -> Self{    
        self.push("Bar".to_string())    
    }
}

标签: rust

解决方案


impl AppendBar for Vec<String> {
    fn append_bar(self) -> Self{
        let mut bar = vec![String::from("Bar")];
        bar.push(self);
        bar
    }
}

因为self是 aVec<String>并且您不能将 a 推Vec<String>入 a Vec<String>(错误消息告诉您:“预期String得到Vec<String>”)。

impl AppendBar for Vec<String> {
    fn append_bar(self) -> Self{
        let bar_vec = vec!["Bar".to_string()];
        self.append(bar_vec)
    }
}

因为Vec::append什么都不返回,所以你需要self自己返回(或者&mut self作为参数什么都不返回)。

impl<T> AppendBar<T> for Vec<T> {
    fn append_bar(self) -> Self{    
        self.push("Bar".to_string())    
    }
}

因为"Bar".to_string()不保证T对所有类型都是 a T


推荐阅读