generic and type inference
tags: learning go programming
content
- when we have a generic function like:
func Clone[T ~[]E, E any](s T) T {}- we can call it like:
type MySlice []string
ms := MySlice{"hello", "world"}
newMs := Clone(ms)- in this process, two type inferences have happened
- the type of
msis inferred byMySlice{"hello", "world"} - input type of
Cloneis inferred
- the type of
- if there’s NO type inference:
var ms MySlice
ms = MySlice{"hello", "world"}
var newMs MySlice
newMs = Clone[MySlice, string](ms)- notice that if there’s NO type inference, the input type of
Cloneneeds to be declared explicitly