Go是否支持模板或泛型?

I know that Go doesn't have classes in the traditional OOP sense, but Go does provide a notion of interfaces that allows you do most of the OOP things you'd want to do.

BUT, does Go allow for something like creating a templated class? For instance, I'm reading through the source code for the container/list package. It defines a list and the list's associated methods. But in all methods, the values contained in the list are of type interface{} -- so, of any type. Is there any way to create a list that is constrained to only hold values of a particular type? int, string, Fruit... whatever.

Basically what @FUZxxl said.

Generics? Not at this time.

Templates? Not quite. There are third-party projects like gotgo which aim to add template support by pre-processing files. However, gotgo is quite dead as far as I know.

Your best option is to use interfaces or reflection for the time being.

If you really want to use reflection, note that the reflect package offers a way to fill a typed function variable with generic (reflected) content. You can use this to use types the compiler can check with your reflection based solutions.

Newer than gotgo, there's a code-generation-based package called "gen".

http://clipperhouse.github.io/gen/

gen is an attempt to bring some generics-like functionality to Go, with inspiration from C#’s Linq, JavaScript’s Array methods and the underscore library. Operations include filtering, grouping, sorting and more.

The pattern is to pass func’s as you would pass lambdas in Linq or functions in JavaScript.