Let's say I define the following interface in a Go library:
type Task interface {
Do() error
}
func Register(task Task) { ... }
func GetId(task Task) int64 { ... }
In Register()
, the library associates a unique int64
with each task instance. GetId()
must return the identifier for the given task.
My initial idea was to store the association as a map[Task]int64
. This seems to work fine, but I was told that it would break if an object implementing Task
was not equality-comparable (for example, a struct
containing a map
). I still need to check if this is true.
I was going to try and use a slice of struct { task Task; id int64 }
instead and just iterate over it, but that would still require equality comparable Task
instances. And AFAIU there is no identity comparison in Go.
How can I have a robust mapping from Task
instances to their ID?
EDIT: Both solutions proposed so far work, but they have the disadvantage that every Task implementation has to include some repetitive code to handle the IDs. I could provide that code in a TaskBase struct
that could be embedded, but ideally I would prefer a solution that doesn't require implementations to even know about the IDs (they are internal to the library and have no meaning outside of it).