我正在尝试删除以下示例中的重复项:
struct User {
reference: String,
email: String,
}
fn main() {
let mut users: Vec<User> = Vec::new();
users.push(User {
reference: "abc".into(),
email: "test@test.com".into(),
});
users.push(User {
reference: "def".into(),
email: "test@test.com".into(),
});
users.push(User {
reference: "ghi".into(),
email: "test1@test.com".into(),
});
users.sort_by(|a, b| a.email.cmp(&b.email));
users.dedup();
}
Run Code Online (Sandbox Code Playgroud)
我收到了(预期)错误
error[E0599]: no method named `dedup` found for type `std::vec::Vec<User>` in the current scope
--> src/main.rs:23:11
|
23 | users.dedup();
| ^^^^^
|
Run Code Online (Sandbox Code Playgroud)
如何从删除重复users的email值?我可以实现dedup()功能struct User还是我必须做其他事情?
如果您查看文档Vec::dedup,您会注意到它位于以下标记的小部分中:
impl<T> Vec<T>
where
T: PartialEq<T>,
Run Code Online (Sandbox Code Playgroud)
这意味着只有满足给定的约束时,它下面的方法才存在.在这种情况下,dedup不存在是因为User没有实现PartialEq特征.在这种特殊情况下,您可以导出它:
= note: the method `dedup` exists but the following trait bounds were not satisfied:
`User : std::cmp::PartialEq`
Run Code Online (Sandbox Code Playgroud)
推导出所有适用的特征通常是一个好主意; 它很可能是一个好主意,也得出PartialEq,Eq和Clone.
| 归档时间: |
|
| 查看次数: |
842 次 |
| 最近记录: |