Search code examples
gogenericsmethodstypes

Defining type as generic type instantiation


In the example below, I am trying to define a PreciseAdder type that would simplify the use of an instantiated generic type. Unfortunately, the go compiler seems to think that the methods defined on the generic type do not apply on the PreciseAdder type. I know I can solve this through composition, but is there a way of making this work with type definition and if not, what is the reason?

package main

type Addable interface {
    Add()
}

type Adder[T Addable] struct{}

func (a Adder[T]) DoAdd(){}

type PreciseAddable struct{}

func (p PreciseAddable)Add(){}

type PreciseAdder Adder[PreciseAddable]

func main() {
    var p PreciseAdder
    p.DoAdd()
}

Solution

  • This:

    type PreciseAdder Adder[PreciseAddable]
    

    Is a type declaration, more specifically a type definition. It creates a new type, all methods stripped.

    Instead use a type alias which will retain all methods, it just introduces a new identifier to refer to the same type:

    type PreciseAdder = Adder[PreciseAddable]
    

    (Note the = sign between the identifier and the type.)