The method `get` exists but the following trait bounds were not satisfied

Hello ! I have a problem with a simple HashMap:

use std::collections::HashMap;
use std::time::Instant;

pub struct Blinker<T> {
    items: HashMap<T, Instant>
}

impl<T> Blinker<T> {
    pub fn visible(&mut self, blink_ms: i32, key: T) -> bool {
        if let Some(instant) = self.items.get(&key) {
            let elapsed = instant.elapsed().as_millis();
            if elapsed < blink_ms as u128 {
                return false
            } else if elapsed <= (blink_ms * 2) as u128 {
                return true
            }
        }

        self.items.insert(key, Instant::now());
        false
    }
}
error[E0599]: no method named `get` found for type `std::collections::HashMap<T, std::time::Instant>` in the current scope
  --> src/util.rs:18:43
   |
18 |         if let Some(instant) = self.items.get(&key) {
   |                                           ^^^ method not found in `std::collections::HashMap<T, std::time::Instant>`
   |
   = note: the method `get` exists but the following trait bounds were not satisfied:
           `T : std::cmp::Eq`
           `T : std::hash::Hash`

error[E0599]: no method named `insert` found for type `std::collections::HashMap<T, std::time::Instant>` in the current scope
  --> src/util.rs:27:20
   |
27 |         self.items.insert(key, Instant::now());
   |                    ^^^^^^ method not found in `std::collections::HashMap<T, std::time::Instant>`
   |
   = note: the method `insert` exists but the following trait bounds were not satisfied:
           `T : std::cmp::Eq`
           `T : std::hash::Hash`

How can i solve missing following trait satisfaction ? Or indicate T can be simple type like i32, char, String ...

Solved !

pub struct Blinker<T> where T: std::cmp::Eq + std::hash::hash {
[...] 
impl<T> Blinker<T> where T: std::cmp::Eq + std::hash::Hash {
[...]
1 Like

Note that you don't need bounds on the struct, bounds on the impl would be enough.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.