Generic Structs with Go

Issue

What is the equivalent of this C# code in Go, how can I build it

    class ModelX<T>
    {
        public T Data { get; set; }
    }

    ModelX<int>

I have tried something like:

    type ModelX<T> struct {
        ModelY
        Data []T
    }

    m := ModelX<T>

How to do this? Is that possible?

Solution

Starting with Go 1.18 (soon), you can define generic types:

type ModelX[T any] struct {
    Data []T
}

A generic type must be instantiated when used, and instantiation requires a type parameter list:

func main() {
    // passing int as type parameter
    modelInt := ModelX[int]{Data: []int{1, 2, 3}}
    fmt.Println(modelInt.Data) // [1 2 3]
}

An important detail is that — unlike functions1 —, generic types must always supply all type parameters upon instantiation2. For example:

type Foo[T any, PT *T] struct {
    val T
    ptr PT
}

must be instantiated with both types:

func main() {
    v := int64(20)
    foo := Foo[int64, *int64]{val:v, ptr: &v}

    fmt.Println(foo)
}

GoTip Playground: https://gotipplay.golang.org/p/pV0xPCewUdB


1: The quote from the specifications is "Calls to parameterized functions may provide a (possibly partial) type argument list, or may omit it entirely if the omitted type arguments are inferrable from the ordinary (non-type) function arguments.". This quote excludes parametrized types

2: in early beta releases, the type param list in generic types could be partial; this feature has been disabled.

Answered By – blackgreen

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.