what’s unnamed type in Go

tags: learning go programming

content

  • a type that’s defined inline without specifically using type keyword
func Clone[E any](arg []E) []E {
	return append([]E(nil), arg...)
}
  • in this example, E is defined without using any type keyword
type MySlice []string
mySlice := MySlice{"hello", "world"}
newSlice := Clone(ms)
fmt.Printf("%T\n", mySlice)
fmt.Printf("%T\n", newSlice)
  • is newSlice of type MySlice or []string?

    • answer: it’s []string
  • confusion

    • Clone’s signature says it takes in []E and returns []E
    • im passing in MySlice, why isn’t Clone returning MySlice, but []string instead
  • answer

    • Clone is taking in []E, and MySlice is 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 E becomes string
    • go-type-inference-1
  • if we have type MySlice []string
    • MySlice is a named type
    • because MySlice is defined with type keyword
  • if we have func MyFunc(s []MySlice) {}
    • []MySlice is an unnamed type
    • because there’s no name to it!
      • []MySlice is a slice of MySlice, that’s not a name
      • a name should be something like MySlice

up

down

reference