mitems.nim 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import sets, hashes
  2. type
  3. Fruit* = ref object
  4. id*: int
  5. # Generic implementation. This doesn't work
  6. EntGroup*[T] = ref object
  7. freed*: HashSet[T]
  8. proc hash*(self: Fruit): Hash = hash(self.id)
  9. ##
  10. ## VVV The Generic implementation. This doesn't work VVV
  11. ##
  12. proc initEntGroup*[T: Fruit](): EntGroup[T] =
  13. result = EntGroup[T]()
  14. result.freed = initHashSet[Fruit]()
  15. var apple = Fruit(id: 20)
  16. result.freed.incl(apple)
  17. proc get*[T: Fruit](fg: EntGroup[T]): T =
  18. if len(fg.freed) == 0: return
  19. # vvv It errors here
  20. # type mismatch: ([1] fg.freed: HashSet[grouptest.Fruit])
  21. for it in fg.freed:
  22. return it
  23. ##
  24. ## VVV The Non-Generic implementation works VVV
  25. ##
  26. type
  27. # Non-generic implementation. This works.
  28. FruitGroup* = ref object
  29. freed*: HashSet[Fruit]
  30. proc initFruitGroup*(): FruitGroup =
  31. result = FruitGroup()
  32. result.freed = initHashSet[Fruit]()
  33. var apple = Fruit(id: 20)
  34. result.freed.incl(apple)
  35. proc getNoGeneric*(fg: FruitGroup): Fruit =
  36. if len(fg.freed) == 0: return
  37. for it in fg.freed:
  38. return it
  39. proc `$`*(self: Fruit): string =
  40. # For echo
  41. if self == nil: return "Fruit()"
  42. return "Fruit(" & $(self.id) & ")"