Generic function implementation:
/*
* "generic" is a KIND of types, just like "struct", "map", "interface", etc...
* "T" is a generic type (a type of kind generic).
* var t = T{int} is a value of type T, values of generic types looks like a "normal" type
*/
type T generic {
int
float64
string
}
func Sum(a, b T{}) T{} {
return a + b
}
Function caller:
Sum(1, 1) // 2
// same as:
Sum(T{int}(1), T{int}(1)) // 2
Generic struct implementation:
type ItemT generic {
interface{}
}
type List struct {
l []ItemT{}
}
func NewList(t ItemT) *List {
l := make([]t)
return &List{l}
}
func (p *List) Push(item ItemT{}) {
p.l = append(p.l, item)
}
Caller:
list := NewList(ItemT{int})
list.Push(42)
var f func(a, b int) int = func(a, b int) int { return Sum(a, b) }