Home > Mobile >  Is it possible to define generic function with custom structs?
Is it possible to define generic function with custom structs?

Time:12-21

Let's say I have two different structs:

type One struct {
  Id string
  // Other fields
}

type Two struct {
  Id string
  // Other fields
}

Is it possible to define a function that accepts both One and Two without explicitly listing them as options?

E.g. I am looking for something like this:

type ModelWithId struct {
  Id string
}

func Test[M ModelWithId](m M) {
  fmt.PrintLn(m.Id)
}

one := One { Id: "1" }
Test(one) // Prints 1

I don't want to use funcTest[M One | Two](m M), because I'll likely have 10 structs and I don't want to come back to the function every time I add a new struct to the codebase.

CodePudding user response:

Generics constraints the type parameter behaviours using methods, so you need to rewrite your code as:

type One struct {
    id string
}

func (o *One) Id() string {
    return o.id
}

then your use site would become:

type ModelWithId interface {
    Id() string
}

func Test[M ModelWithId](m M) {
    fmt.Println(m.Id())
}
  • Related