Skip to content

Instantly share code, notes, and snippets.

@neumachen
Forked from anton-yurchenko/golang-generic-struct.md
Created September 19, 2023 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neumachen/5b6c3a49523d0e470eb651621d15a723 to your computer and use it in GitHub Desktop.
Save neumachen/5b6c3a49523d0e470eb651621d15a723 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment