1

I am trying to DRY my code by writing generic function

Here struct I and J both have New() method defined

package main

import (
    "fmt"
)

type Ifs interface {
    I | J
}

type I struct {
}

type J struct {
}

func (i I) New() {
    fmt.Println("I")

}

func (j J) New() {
    fmt.Println("J")
}

func caller[T Ifs](arg T) {
    arg.New() // error here
}

func main() {
    caller[I](I{})
    caller[J](I{})
}

Here at arg.New() I am getting a compile time error

arg.New undefined (type T has no field or method New)

How should we achieve this?

Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40

0 Answers0