From the course: Go for Developers: Practical Techniques for Effective Coding

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Generic types

Generic types

- In addition to functions, types can also be generic. If we consider building a data store, we might define a generic type to represent a model. So here, we define a model interface that defines a constraint that all implementations of the model interface must satisfy. The model interface has a type constraint T, which is the constraints.Ordered constraint. This constraint is now available for use on the interfaces methods. For example, we can return type T from the ID method. Now, in order to implement the model interface, a type needs an ID method that returns a type listed in the ordered constraint. Let's create a new type User that implements the model interface. The ID method on the user type will return a string as the type of ID, which is available in the ordered constraint. We can also define concrete types like structs that use generics. So here, we are defining a Store struct type that has two constraints, K, which is the Ordered constraint, and M, which is the Model we…

Contents