deconstructing type parameters

tags: learning go programming

content

  • when we have a generic function like:
func Clone[T ~[]E, E any](s T) T {}
  • the type parameters [T ~[]E, E any] mean:

    • Clone takes in a type T
    • type T’s underlying type (~) is a slice of type any
  • we are using one type parameter E any to define another type parameter T ~[]E

  • we can have more complex type parameters

    • e.g., we are cloning strings:
func StringClone[T ~[]E, E interface { String() string }](s T) T {}
  • this means the input type has to have a String() string method

up

down

reference