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
    1. the type of ms is inferred by MySlice{"hello", "world"}
    2. input type of Clone is inferred
  • 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 Clone needs to be declared explicitly

up

down

reference