Interfaces
Think of a contract when you hear interfaces. An interface is there to guarantee that your struct will have a certain method.
Let's look at this example:
// function to save a note in a json file
func (todo Todo) Save() error {
fileName := "todo.json"
json, err := json.Marshal(todo)
if err != nil {
return err
}
return os.WriteFile(fileName, json, 0644)
}We have a Save() method which requires a struct of the type to-do to be called. But what if we also want to save, for example, a note instead of only a to-do? Then we would have to duplicate this function and use it with note structure.
But with an interface, we can create a "contract" where we can say, these structs can have these methods. Like that, we can call it on both without creating the function twice.
Creating an interface
// certain value has a certain method guarantee
type saver interface {
Save() error
}In this case, we are saying that our structs must have a Save() method which returns an error. It is called saver because in Golang convention, if your interface has only one method you take the method name and add "er" at the end.
Using an interface
Create a function where we can pass our interface:
func saveData(data saver) error {
err := data.Save()
if err != nil {
fmt.Println("Saving the note failed.")
return err
}
fmt.Println("File saved.")
return nil
}After that, we can easily call it on both structs:
userNote.Display()
err = saveData(userNote)
if err != nil {
fmt.Println("Error")
return
}Last updated