首页 > 解决方案 > 有没有办法从 HashSet 中获取对象> 使用自定义借用实现而不是创建新类型?

问题描述

我有一个Student结构,我存储在一个由引用包装HashSet的结构内部,以便它们可以被其他内部结构引用:SchoolRcSchool

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>的来获得对学生的引用:HashSetid

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这里不是最好的选择?

标签: rust

解决方案


推荐阅读