what is generics in Go
tags: learning go programming
content
- generics lets you write one function that can be used for different types
- as long as the types follow some constraints (go-type-constraint)
- this is generic functions
// generic function:
func MyFunc[T TypeConstraint](arg T) T {}- other than generic function, we can also have methods on generic type
type MyMap[K comparable, V any] map[K]V
// methods on generic type
func (m *MyMap[K, V]) GetValues() []V {
var res []V
for _, v := range *m {
res = append(res, v)
}
return res
}