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

问题描述 投票:0回答:1

我希望

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);
}

这会导致错误:

 $ 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<_>`

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

string rust vector traits
1个回答
6
投票

为了使

T
列表可连接,
[T]
需要实现
Join<Separator>

如果你查看哪些东西已经实现了

Join
,你会发现以下条目

impl<S> Join<&str> for [S]
where
    S: Borrow<str>

这意味着,所有实现

Borrow<str>
的内容都可以通过
&str
分隔符连接起来。所以你所要做的就是为你的结构实现
Borrow<str>

use std::borrow::Borrow;

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

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

impl Borrow<str> for Item {
    fn borrow(&self) -> &str {
        &self.string
    }
}

fn main() {
    let items = Vec::from([Item::new("Hello"), Item::new("world")]);
    let string = items.join(" ");
    println!("{}", string);
}
Hello world
© www.soinside.com 2019 - 2024. All rights reserved.