rust 如何在Vec上实现一个可以追加字符串的trait?

pepwfjgg  于 2023-10-20  发布在  其他
关注(0)|答案(4)|浏览(153)

这是从尝试Rustlings运动特质2。这个练习要求我在Vec上实现trait。测试就在那里,他们失败了,这是一个很好的开始。我已经为String做了trait实现,这很容易,但Vec是另一回事。我不确定该方法需要返回什么,它在各种返回中失败。我提供原始代码,我的尝试和错误,我得到我的尝试.希望这就足够了。
原始代码来自Rustlings repo:

// traits2.rs
// 
// Your task is to implement the trait
// `AppendBar' for a vector of strings.
// 
// To implement this trait, consider for
// a moment what it means to 'append "Bar"'
// to a vector of strings.
// 
// No boiler plate code this time,
// you can do this!

// I AM NOT DONE

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

//TODO: Add your code here



#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_vec_pop_eq_bar() {
        let mut foo = vec![String::from("Foo")].append_bar();
        assert_eq!(foo.pop().unwrap(), String::from("Bar"));
        assert_eq!(foo.pop().unwrap(), String::from("Foo"));
    }

}

以及我解决这个问题的尝试

// traits2.rs
//
// Your task is to implement the trait
// `AppendBar' for a vector of strings.
//
// To implement this trait, consider for
// a moment what it means to 'append "Bar"'
// to a vector of strings.
//
// No boiler plate code this time,
// you can do this!

// I AM NOT DONE
use std::clone::Clone;
trait AppendBar {
    fn append_bar(&mut self) -> Self;
}

//TODO: Add your code here
impl<T: Clone> AppendBar for Vec<T> {
    fn append_bar(&mut self) -> Self {
        let bar: T = String::from("Bar");
        self.to_vec().push(bar)
        // self.to_vec()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_vec_pop_eq_bar() {
        let mut foo = vec![String::from("Foo")].append_bar();
        assert_eq!(foo, vec![String::from("Foo"), String::from("Bar")]);
        assert_eq!(foo.pop().unwrap(), String::from("Bar"));
        assert_eq!(foo.pop().unwrap(), String::from("Foo"));
    }
}

编译为错误:

! Compiling of exercises/traits/traits2.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
  --> exercises/traits/traits2.rs:22:22
   |
20 | impl<T: Clone> AppendBar for Vec<T> {
   |      - this type parameter
21 |     fn append_bar(&mut self) -> Self {
22 |         let bar: T = String::from("Bar");
   |                  -   ^^^^^^^^^^^^^^^^^^^ expected type parameter `T`, found struct `std::string::String`
   |                  |
   |                  expected due to this
   |
   = note: expected type parameter `T`
                      found struct `std::string::String`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

error[E0308]: mismatched types
  --> exercises/traits/traits2.rs:23:9
   |
21 |     fn append_bar(&mut self) -> Self {
   |                                 ---- expected `std::vec::Vec<T>` because of return type
22 |         let bar: T = String::from("Bar");
23 |         self.to_vec().push(bar)
   |         ^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::vec::Vec`, found `()`
   |
   = note: expected struct `std::vec::Vec<T>`
           found unit type `()`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0308`.

我已经读了一遍又一遍书中的建议部分和特点,但这超出了我的能力。我相信这是一个简单的解决方案,但我看不到它。

4xy9mtcn

4xy9mtcn1#

有几个问题:

  • 您尝试将String推送到泛型Vec<T>,其中T可以是任何类型!
  • 方法签名与赋值不同:你的方法被定义为
fn append_bar(&mut self) -> Self

,但它应该是

fn append_bar(self) -> Self
  • 您尝试返回Vec::push的结果,但此方法不返回任何内容。

要修复第一个问题,请为Vec<String>而不是Vec<T>实现trait。这就是作业的要求

// Your task is to implement the trait
// `AppendBar' for a vector of strings.

要解决第二个问题,必须删除&,因此该方法接受 owned 值。
要修复最后一个问题,请在单独的语句中调用Vec::push后返回self

self.push(bar);
self
iyfjxgzm

iyfjxgzm2#

阿洛索的回答有出入安德烈也给了。
当你取self时:

fn append_bar(self) -> Self {
    self.push("Bar".to_owned());
    self
}

你正在接受一个可变的Vec

let mut foo = vec![String::from("Foo")].append_bar();
assert_eq!(foo.pop().unwrap(), String::from("Bar"));
assert_eq!(foo.pop().unwrap(), String::from("Foo"));

即使变量foo被声明为可变的,方法append_bar()也接受一个不可变的变量。你不需要借用self,因为你并没有试图获得全部所有权,你只是试图修改驻留在该变量中的现有数据。正确答案是

fn append_bar(mut self) -> Self {
    self.push("Bar".to_owned()); // || .to_string() || String::from("Bar") 
    // Whatever gets the point across. As the String literal is essentially a "Borrowed" string.
    self
}

append_bar()的作用域中,您试图改变String的集合,并返回带有附加字符串的集合。

xxe27gdn

xxe27gdn3#

我相信这个问题的正确答案应该是这样的:

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

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

yyhrrdl84#

感谢@Aloso的帮助和Jussi,我也设法让这个例子工作。
为了编译,需要进行Mutation,所以我最终得到了如下编译的代码:

// traits2.rs
//
// Your task is to implement the trait
// `AppendBar' for a vector of strings.
//
// To implement this trait, consider for
// a moment what it means to 'append "Bar"'
// to a vector of strings.
//
// No boiler plate code this time,
// you can do this!

// I AM NOT DONE

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

//TODO: Add your code here
impl AppendBar for Vec<String> {
    fn append_bar(&mut self) -> Self {
        self.push(String::from("Bar"));
        self.to_vec()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_vec_pop_eq_bar() {
        let mut foo = vec![String::from("Foo")].append_bar();
        assert_eq!(foo, vec![String::from("Foo"), String::from("Bar")]);
        assert_eq!(foo.pop().unwrap(), String::from("Bar"));
        assert_eq!(foo.pop().unwrap(), String::from("Foo"));
    }
}

相关问题