how does Go infer types

tags: learning go programming

content

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 ms is type MySlice, but ms2 is []string

  • for Clone

    • Clone is a generic function, Go needs to infer the type of input argument
    • Clone is expecting a list of any type: arg is []E, and E is any
  • when we passed in MySlice to Clone:

    • Go sees it’s NOT []E
    • so it tries to see through the E passed in, which is MySlice in this case
    • by see through, Go finds the underlying type of MySlice, which is []string
    • Go decides that E in this call is string
  • that’s why the function returns []string (which is []E with E being string)

up

down

reference