Skip to content

Instantly share code, notes, and snippets.

@plorenz
Created October 7, 2022 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save plorenz/ce18ffb059ce5b42ad7ac43f14287f22 to your computer and use it in GitHub Desktop.
Save plorenz/ce18ffb059ce5b42ad7ac43f14287f22 to your computer and use it in GitHub Desktop.
go generics test
package main
import (
"errors"
"fmt"
)
type Example interface {
Init(config map[string]interface{})
}
type ExampleFactory[T Example] struct {
config map[string]interface{}
}
func (self *ExampleFactory[T]) Get() T {
var result = *new(T) // result := new(T) won't work
result.Init(self.config)
return result
}
type Db struct {
vals map[string]bool
}
func (self *Db) Init(config map[string]interface{}) {
if self == nil {
panic(errors.New("db is nil"))
}
self.vals = map[string]bool{"initialized" : true}
}
func main() {
factory := &ExampleFactory[*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