-
Notifications
You must be signed in to change notification settings - Fork 5
Generic Struct
Tao Wen edited this page Jul 19, 2017
·
27 revisions
For generic struct provider
package collection
/*
example interface
type IntStringPair interface {
First() int
SetFirst(val int)
Second() string
SetSecond(val string)
}
*/
var pair = generic.
Struct("pair").
Params("I", "interface of the typed pair").
Source(`
{{ $T1 := .I | method "First" | returnType }}
{{ $T2 := .I | method "Second" | returnType }}
type {{ .structName }} struct {
first {{ $T1 }}
second {{ $T2 }}
}
func (pair *{{ .structName }}) SetFirst(val {{ $T1|name }}) {
pair.first = val
}
func (pair *{{ .structName }}) First() {{ $T1|name }} {
return pair.first
}
`)
var NewPair = generic.
Func("NewPair").
Params("I", "interface of the typed pair").
ImportStruct(pair).
Source(`
{{ $pair = expand "pair" "I" .I }}
func {{ .funcName }} () {{ .I|name }} {
return &{{ $pair }}{}
}
`)For generic struct user
type IntStringPair interface {
First() int
SetFirst(val int)
Second() string
SetSecond(val string)
}
newPair := generic.Expand(collection.NewPair,
"I", reflect.TypeOf(new(IntStringPair)).Elem()).
(func() IntStringPair)
pair := newPair()
pair.First() // 0
pair.SetFirst(1)
pair.First() // 1