what’s unnamed type in Go
tags: learning go programming
content
- a type that’s defined inline without specifically using
typekeyword
func Clone[E any](arg []E) []E {
return append([]E(nil), arg...)
}- in this example,
Eis defined without using anytypekeyword
type MySlice []string
mySlice := MySlice{"hello", "world"}
newSlice := Clone(ms)
fmt.Printf("%T\n", mySlice)
fmt.Printf("%T\n", newSlice)-
is
newSliceof typeMySliceor[]string?- answer: it’s
[]string
- answer: it’s
-
confusion
Clone’s signature says it takes in[]Eand returns[]E- im passing in
MySlice, why isn’tClonereturningMySlice, but[]stringinstead
-
answer
Cloneis taking in[]E, andMySliceis passed in (not[]MySlice)- so, Go is inferring the underlying type of
MySlice, which is[]string, which fits in the type parameter[]E - so, type
Ebecomesstring - go-type-inference-1
how does this link back to unnamed type?
- if we have
type MySlice []stringMySliceis a named type- because
MySliceis defined withtypekeyword
- if we have
func MyFunc(s []MySlice) {}[]MySliceis an unnamed type- because there’s no name to it!
[]MySliceis a slice ofMySlice, that’s not a name- a name should be something like
MySlice