传送门: https://blog.golang.org/generics-next-step
官方示例:
package main
import (
"fmt"
)
// The playground now supports parentheses or square brackets (only one at
// a time) for generic type and function declarations and instantiations.
// By default, parentheses are expected. To switch to square brackets,
// the first generic declaration in the source must use square brackets.
func Print[type T](s []T) {
for _, v := range s {
fmt.Print(v)
}
}
func main() {
Print([]string{"Hello, ", "playground\n"})
}
High Level Overview:
- Functions can have an additional type parameter list introduced by the keyword type: func F(type T)(p T) { ... }.
- These type parameters can be used by the regular parameters and in the function body.
- Types can also have a type parameter list: type M(type T) []T.
- Each type parameter can have an optional type constraint: func F(type T Constraint)(p T) { ... }
- Type constraints are interface types.
- Interface types used as type constraints can have a list of predeclared types; only types whose underlying type is - one of those types can implement the interface.
- Using a generic function or type requires passing type arguments.
- Type inference permits omitting the type arguments in common cases.
- If a type parameter has a type constraint its type argument must implement the interface.
- Generic functions may only use operations permitted by the type constraint.