What are Interfaces in Golang?
An interface type is defined as a set of method signatures.
Syntax: type var_name interface {}
An interface describes behaviors. Hence you put methods(i.e. behaviors) inside it.Let me take an example to explain this. Let chef be an interface who has methods 1) Cut and 2) Cook. We can also say that anyone who can 1) Cut and 2) Cook is a Chef. In order to explain the above statement in more detail here is one more example: In this example we take a structure called anyPerson. If anyPerson implements 1) Cut and 2) Cook; then anyPerson is a chef :D
package main
import (
"fmt"
)
type chef interface {
cut()
cook()
}
type anyPerson struct {
}
func (a anyPerson) cut() {
fmt.Println("anyPerson can cut... chop chop chop")
}
func (a anyPerson) cook() {
fmt.Println("anyPerson can cook...sizzle sizzle pop!")
}
func main() {
aP := anyPerson{}
aP.cut()
aP.cook()
}
Another example with a slight variation is here!
Interfaces are implemented implicitly. A type implements an interface by implementing its methods or we can also say that any structure that implements all the behaviors(i.e. methods) of an interface becomes an interface.
type Cruder interface {
Create(conn *dbConnection, name string, amount int) (*models.SuccessStruct, error)
Read(conn *dbConnection) (*[]models.Customer, error)
Update(conn *dbConnection, n string, amt int, id int) (*models.SuccessStruct, error)
Delete(conn *dbConnection, id int) (*models.SuccessStruct, error)
}
type myStore struct {
}
//Now, we will make myStore an interface.
func (m myStore) Create(conn *dbConnection, name string, amount int) error {
fmt.Println("This is the Create Method")
}
return nil
}
func (m myStore) Read(conn *dbConnection, name string, amount int) error {
fmt.Println("This is the Read Method")
}
return nil
}
func (m myStore) Update(conn *dbConnection, name string, amount int) error {
fmt.Println("This is the Update Method")
}
return nil
}
func (m myStore) Delete(conn *dbConnection, name string, amount int) error {
fmt.Println("This is the Delete Method")
}
return nil
}
Why do we use Interfaces in Golang?
I have listed a few advantages of interfaces in Go:
(u userDefinedStructure) DB.Scan() {
// Unmarshall the data into 'u'
}
A few links I referred to while writing this article: