Search code examples
gointerfacecode-generation

Retype code but retain existing interface


I would like to retype an existing type but retain its interface inheritance.

so example code:

interface interface1 {
  func interfaceFunc1()
}

type basicStruct struct {
  param int
}

type retyped1 basicStruct
type retyped2 basicStruct

func (basicStruct) interfaceFunc1() {
  // does stuff
}

func getTyped1() retyped1 {
  return basicStruct{param:0}
}

func getTyped2() retyped2 {
  return basicStruct{param:1}
}

func main() {
  type1 := getTyped1()
  type2 := getTyped2()

  // These lines do not compile
  type1.interfaceFunc1()
  type2.interfaceFunc1()
}

Due to a code generation library I am using I can't just have it return basic struct it has to return retyped1 and retyped2. But I also need to use the interface functions. Is there anyway to use the interface functions without some silly copy and paste of all the interface functions which do the exact same thing except like 1 if statement in a couple hundred lines?


Solution

  • As Burak Serdar pointed, in golang there is 2 different ways to define type:

    type retyped1 struct {
      basicStruct
    }
    

    Which inherits methods of basicStruct, and

    type retyped2 basicStruct
    

    Which creates new struct with same fields as basicStruct, but not it's methods.

    For your particular situation you could use type aliases, which is actually just another name for type, so you can reuse it's methods with it:

    type retyped1 = basicStruct