Skip to content

Instantly share code, notes, and snippets.

@anton-yurchenko
Created April 16, 2022 08:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save anton-yurchenko/78e66b699863cce2520cd4dcb22fbd78 to your computer and use it in GitHub Desktop.
Save anton-yurchenko/78e66b699863cce2520cd4dcb22fbd78 to your computer and use it in GitHub Desktop.
GoLang Generic Struct

The following snippet contains an example for GoLang Generics for Structs:

package main

import "fmt"

// Structs definition
type ObjectOne struct {
	Name string      `json:"name"`
	Data interface{} `json:"data"`
}

func (a *ObjectOne) GetName() string {
	return a.Name
}

type ObjectTwo struct {
	Name   string      `json:"name"`
	Data   interface{} `json:"data"`
	Option bool        `json:"option"`
}

func (a *ObjectTwo) GetName() string {
	return a.Name
}

// Generics
type objectType interface {
	*ObjectOne | *ObjectTwo
	GetName() string
}

type Object[T objectType] struct {
	Body T
}

func New[T objectType](object T) *Object[T] {
	return &Object[T]{
		Body: object,
	}
}

func (o *Object[T]) PrintName() string {
	return o.Body.GetName()
}

func main() {
	o := New(&ObjectOne{
		Name: "Object-1",
		Data: 123,
	})
	fmt.Printf("%+v\n", *o.Body)

	t := New(&ObjectTwo{
		Name:   "Object-2",
		Data:   "payload",
		Option: true,
	})
	fmt.Printf("%+v\n", *t.Body)

	// Usage
	fmt.Printf("%+v\n", o.PrintName())
	fmt.Printf("%+v\n", t.PrintName())
}

Output:

{Name:Object-1 Data:123}
{Name:Object-2 Data:payload Option:true}
Object-1
Object-2
@pokeyaro
Copy link

pokeyaro commented Feb 18, 2023

The generics in go seem to have no way to allow the real implementation definition of the struct to be free. Ideally, T is defined as any type, and then the required struct type is passed in when using it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment