0

I am trying to implement something like

struct Student {
    name: String,
    gpa: f32,
    // ...
}

struct StudentList {
    items: HashMap<&String, Student>,
}

impl StudentList {
    pub fn set(&mut self, student: Student) {
        self.items.insert(student.name, student)
    }
}

Yet the issue is that if I use &String I need to provide a lifetime. How do I specify the key has the same lifetime as the value?

Herohtar
  • 4,958
  • 4
  • 31
  • 39
xis
  • 23,504
  • 9
  • 41
  • 58
  • Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) The short answer is "you don't, it's rarely useful." The longer answer is "sometimes you can do this if you know what you're doing." – cdhowie Apr 27 '22 at 07:09
  • Another, better duplicate: [Lifetimes in HashMap where key refers to value](https://stackoverflow.com/q/61020835/501250) – cdhowie Apr 27 '22 at 07:30

0 Answers0