如何允许自定义类型的 Vec 与 &str 连接?

Ric*_*ann 1 string vector traits rust

我想要一个Vec<CustomType>可以加入的&str。这是我到目前为止所尝试过的:

#[derive(Debug)]
struct Item {
    string: String,
}

impl Item {
    pub fn new(string: impl Into<String>) -> Self {
        Self {
            string: string.into(),
        }
    }

    pub fn to_string(&self) -> &String {
        &self.string
    }
}

impl From<&Item> for &String {
    fn from(item: &Item) -> Self {
        &item.string
    }
}

impl From<&Item> for &str {
    fn from(item: &Item) -> Self {
        &item.string.to_string()
    }
}

fn main() {
    let items = Vec::from([Item::new("Hello"), Item::new("world")]);
    let string = items.join(" ");
    println!("{}", string);
}
Run Code Online (Sandbox Code Playgroud)

这会导致错误:

 $ rustc jointrait.rs 
error[E0599]: the method `join` exists for struct `Vec<Item>`, but its trait bounds were not satisfied
  --> jointrait.rs:32:24
   |
32 |     let string = items.join(" ");
   |                        ^^^^ method cannot be called on `Vec<Item>` due to unsatisfied trait bounds
   |
   = note: the following trait bounds were not satisfied:
           `[Item]: Join<_>`
Run Code Online (Sandbox Code Playgroud)

rustc 帮助只是说缺少某些方法,但是通过谷歌搜索错误,我找不到我需要实现哪个方法/特征。

Fin*_*nis 6

为了使 s 列表T可连接,[T]需要实现Join<Separator>.

如果您查看已经实现的内容Join,您会发现以下条目

impl<S> Join<&str> for [S]
where
    S: Borrow<str>
Run Code Online (Sandbox Code Playgroud)

这意味着,所有实现的东西都Borrow<str>可以通过分隔符连接起来&str。所以你所要做的就是实现Borrow<str>你的结构:

impl<S> Join<&str> for [S]
where
    S: Borrow<str>
Run Code Online (Sandbox Code Playgroud)
Hello world
Run Code Online (Sandbox Code Playgroud)