I am trying to define a generic function in Go that accepts values that have certain fields, for example, ID int
. I have tried several approaches but none seems to work. Here is an example of what I have tried.
package main
import (
"fmt"
)
func Print[T IDer](s T) {
fmt.Print(s.ID)
}
func main() {
Print(Person{3, "Test"})
}
type IDer interface {
~struct{ ID int }
}
type Person struct {
ID int
Name string
}
type Store struct {
ID int
Domain string
}
And here is the playground link: https://gotipplay.golang.org/p/2I4RsUCwagF
In the example above, I want to guarantee every value passed to the Print
function has a property ID int
, which is also accessible in the function. Is there any way I can achieve this in Go without defining a method in an interface (e.g., GetID() int
)?