解答

  1. use std::collections::HashMap;
  2. use std::hash::Hash;
  3. /// Counter counts the number of times each value of type T has been seen.
  4. struct Counter<T> {
  5. values: HashMap<T, u64>,
  6. }
  7. impl<T: Eq + Hash> Counter<T> {
  8. /// Create a new Counter.
  9. fn new() -> Self {
  10. Counter { values: HashMap::new() }
  11. }
  12. /// Count an occurrence of the given value.
  13. fn count(&mut self, value: T) {
  14. *self.values.entry(value).or_default() += 1;
  15. }
  16. /// Return the number of times the given value has been seen.
  17. fn times_seen(&self, value: T) -> u64 {
  18. self.values.get(&value).copied().unwrap_or_default()
  19. }
  20. }
  21. fn main() {
  22. let mut ctr = Counter::new();
  23. ctr.count(13);
  24. ctr.count(14);
  25. ctr.count(16);
  26. ctr.count(14);
  27. ctr.count(14);
  28. ctr.count(11);
  29. for i in 10..20 {
  30. println!("saw {} values equal to {}", ctr.times_seen(i), i);
  31. }
  32. let mut strctr = Counter::new();
  33. strctr.count("apple");
  34. strctr.count("orange");
  35. strctr.count("apple");
  36. println!("got {} apples", strctr.times_seen("apple"));
  37. }