You can create a new interface in the Go type system by using the type keyword, giving the new type a name, and then basing that new type on the interface type, Listing 8.1.
Interfaces define behavior, therefore they are only a collection of methods. Interfaces can have zero, one, or many methods.
The larger the interface, the weaker the abstraction. – Rob Pike
It is considered to be non-idiomatic to have large interfaces. Keep the number of methods per interface as small as possible, Listing 8.2. Small interfaces allow for easier interface implementations, especially when testing. Small interfaces also help us keep our functions and methods small in scope making them more maintainable and testable.
It is important to note that interfaces are a collection of methods, not fields, Listing 8.3. In Go only structs have fields, however, any type in the system can have methods. This is why interfaces are limited to methods only.
Defining a Model Interface
Consider, again, the Insert method for our data store, Listing 8.4. The method takes two arguments. The first argument is the ID of the model to be stored.
The second argument, in Listing 8.4, should be one of our data models. However, because we are using an empty interface, any type from int to nil may be passed in.
To prevent types, such as a function definition, Listing 8.5, that aren't an expected data model, we can define an interface to solve this problem. Since the Insert function needs an ID for insertion, we can use that as the basis for an interface.
To implement the Model interface, Listing 8.6, a type must have a ID() int method. We can cleanup the Insert method's definition by accepting a single argument, the Model interface, Listing 8.7.
Now, the compiler and/or runtime will reject any type that, such as string, byte, and func(), that doesn't have a ID() int method, Listing 8.8.
Implementing the Interface
Finally, let's create a new type, User, that implements the Model interface, Listing 8.9.
When we update the tests, Listing 8.10, to use the User type, our tests now pass.