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

Unlock this course with a free trial

Join today to access over 24,900 courses taught by industry experts.

Using interfaces

Using interfaces

- Consider again the insert method for our data store. The method takes two arguments. The first argument is the idea of the model to be stored. The second argument 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 ints or floats that aren't an expected data model, we can define an interface to help keep unwanted types out of the insert method. Since the insert function needs an ID, we can use that as the basis for an interface. So we'll define a model interface that has an ID method that returns an int. To implement the model interface a type must have an ID method that returns an int. So first, we need to stop using any as the value type for the data store, and instead use the model interface. Then we can clean up the insert method's definition by accepting a single argument, the model interface. We can use the ID method on the model as the key to the data store. Next, we can update…

Contents