rust - 有没有办法从 HashSet 中获取对象> 使用自定义借用实现而不是创建新类型?
问题描述
我有一个Student
结构,我存储在一个由引用包装HashSet
的结构内部,以便它们可以被其他内部结构引用:School
Rc
School
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
#[derive(Debug, Eq)]
struct Student {
id: usize,
// other stuff
}
impl Hash for Student {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl PartialEq for Student {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
struct School {
students: HashSet<Rc<Student>>,
// other stuff
}
impl School {
fn new() -> Self {
Self {
students: HashSet::new(),
}
}
fn add_student(&mut self) -> usize {
let id = self.students.len();
self.students.insert(Rc::new(Student { id }));
id
}
}
我想实现,这样我就可以通过使用他们Borrow<usize> for Rc<Student>
的来获得对学生的引用:HashSet
id
use std::borrow::Borrow;
impl Borrow<usize> for Rc<Student> {
fn borrow(&self) -> &usize {
&self.id
}
}
impl School {
fn enrol(&mut self, student_id: usize) {
// Need trait Borrow<usize> implemented for Rc<Student> for this to work
if let Some(student) = self.students.get(&student_id) {
println!("Enrolling {:?}", student);
}
}
}
不幸的是,我不能Borrow
按照其他地方的定义那样做,编译器告诉我我需要创建一个新类型。
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/main.rs:26:1
|
26 | impl Borrow<usize> for Rc<Student> {
| ^^^^^-------------^^^^^-----------
| | | |
| | | `std::rc::Rc` is not defined in the current crate
| | `usize` is not defined in the current crate
| impl doesn't use only types from inside the current crate
|
= note: define and implement a trait or new type instead
我理解为什么Borrow for Rc<T>
无法直接实现Borrow
. 目标是拥有一个共享引用,但仍然能够HashSet
通过它们的id
? 也许Rc
这里不是最好的选择?
解决方案
推荐阅读
- c++ - 当静态转换为只移动类型时 Clang 与 GCC
- javascript - 在 map 函数中使用 Promise
- java - 如何使用开关从 sendbroadcast 中清除延迟的未接收传感器数据?
- c# - Entity Framework Core:在“加入”表中添加新条目会删除现有记录
- aem - 将数据传递给 AEM 中的组件
- c# - 使用sqlite内存进行集成测试两个api调用
- c# - 服务器违反了协议。Section=ResponseHeader Detail=CR 后面必须跟 C# Web API 项目中的 LF
- c++ - 将具有可变长度的 C99 静态 3D 数组传递给函数
- python - 如何从 Python Requests/Beautiful Soup 中的某些文本参数中获取特定的 HTML 行
- dictionary - Smalltalk,从计数器字典中增加一个值