Skip to content

Instantly share code, notes, and snippets.

@valsteen
Forked from plorenz/example.go
Last active October 8, 2022 22:58
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 valsteen/617875146e2e03fb7a669ac15419046a to your computer and use it in GitHub Desktop.
Save valsteen/617875146e2e03fb7a669ac15419046a to your computer and use it in GitHub Desktop.
go generics test
package main
import (
"errors"
"fmt"
)
type Default[T any] interface {
Default() T
}
type Example[T any] interface {
Default[T]
Init(config map[string]interface{})
}
type ExampleFactory[T Example[T]] struct {
config map[string]interface{}
}
func (u *ExampleFactory[T]) Get() T {
var builder T
result := builder.Default()
result.Init(u.config)
return result
}
type Db struct {
vals map[string]bool
}
func (d *Db) Default() *Db {
return &Db {
}
}
func (d *Db) Init(config map[string]interface{}) {
if d == nil {
panic(errors.New("db is nil"))
}
d.vals = map[string]bool{"initialized": true}
}
func main() {
factory := &ExampleFactory[*Db]{}
db := factory.Get()
fmt.Printf("Initialized? %v\n", db.vals["initialized"])
}
package main
import (
"errors"
"fmt"
)
type Example interface {
Init(config map[string]interface{})
}
type ExampleFactory[T any, PT interface { *T; Example }] struct {
config map[string]interface{}
}
func (u *ExampleFactory[T, PT]) Get() PT {
var result PT = new(T)
result.Init(u.config)
return result
}
func MakeFactory[T any, PT interface { *T; Example }]() ExampleFactory[T, PT]{
return ExampleFactory[T, PT]{}
}
type Db struct {
vals map[string]bool
}
func (d *Db) Init(config map[string]interface{}) {
if d == nil {
panic(errors.New("db is nil"))
}
d.vals = map[string]bool{"initialized": true}
}
func main() {
factory := MakeFactory[Db]()
db := factory.Get()
fmt.Printf("Initialized? %v\n", db.vals["initialized"])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment