-
-
Save valsteen/617875146e2e03fb7a669ac15419046a to your computer and use it in GitHub Desktop.
go generics test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"]) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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