how does Go infer types
tags: learning go programming
content
- in go-unnamed-type and Deconstructing Type Parameters we have:
type MySlice []string
func Clone[E any](s []E) []E {
return append([]E(nil), s...)
}
ms := MySlice{"hello", "world"}
ms2 := Clone(ms)-
in go-unnamed-type, it’s explained that
msis typeMySlice, butms2is[]string -
for
CloneCloneis a generic function, Go needs to infer the type of input argumentCloneis expecting a list of any type: arg is[]E, andEisany
-
when we passed in
MySlicetoClone:- Go sees it’s NOT
[]E - so it tries to see through the
Epassed in, which isMySlicein this case - by see through, Go finds the underlying type of
MySlice, which is[]string - Go decides that
Ein this call isstring
- Go sees it’s NOT
-
that’s why the function returns
[]string(which is[]EwithEbeingstring)