-
-
Save plorenz/ce18ffb059ce5b42ad7ac43f14287f22 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 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