Go generics where value is comparable and pointer-to-value has methods

5 days ago 4
ARTICLE AD BOX

I have a generic struct that requires passing a generic type that fulfills the constraints where the value is comparable so I can use it in a map index, and the value implements Scanner, ie. type Scanner interface { Scan(Val) }.

For example:

type Key struct { A int B float64 } func (key *Key) Scan(v Val) { *key = Key{int(v.A), v.B} } type Val struct { A float64 B float64 C float64 // ... } type Scanner interface { comparable Scan(Val) } func Test[K Scanner](key K, val Val) { lookup := map[K]bool{} var key2 K key2.Scan(val) }

This doesn't work: (method Scan has pointer receiver). How can I make this work? What is the best practice?

Read Entire Article