What are the benefits of using interfaces in Golang programming?

01 introduction

In the Golang language, an interface type defines a set of method signatures, and the value of an interface type can hold any value that implements these methods.

The interface of golang language is implemented implicitly. Unlike some other programming languages, it uses the implements keyword to explicitly implement the interface. Golang language does not have the implements keyword. As long as a type implements all the methods defined by the interface, it is equivalent to implementing the interface, so it is also called Duck typing.

if something looks like a duck, swims like a duck and quacks like a duck then it's probably a duck.

We have introduced the use of Golang language interface in the previous article. Interested readers can read it. In this article, we will introduce the benefits of using interfaces?

02 benefits of using interfaces

In the Golang language, we can perfectly implement the requirements by using structures and methods. Why use interfaces? In fact, the interface is a tool. Whether we choose to use the interface depends on ourselves. It can make our code more elegant, concise and readable. Let's illustrate these benefits of the interface with a simple example.

Example code:

type Cat struct {

}

func (c Cat) Say() string {
 return "miaow"
}

type Dog struct {

}

func (d Dog) Say() string {
 return "woof woof"
}

func TestSay(t *testing.T) {
 c := Cat{}
 t.Log("Cat say:", c.Say())

 d := Dog{}
 t.Log("Dog say:", d.Say())
}

After reading the above code, we define two structures Cat and Dog and implement the Say method for them respectively. Readers, do you feel that the code is a little repetitive? Because Cat and Dog have the same signature method Say, we can use the interface to reconstruct this code.

Example code:

type Sayer interface {
 Say() string
}

type Cat struct {

}

func (c Cat) Say() string {
 return "miaow"
}

type Dog struct {

}

func (d Dog) Say() string {
 return "woof woof"
}

type Horse struct {

}

func (h Horse) Say() string {
 return "neigh"
}

func TestSay(t *testing.T) {
 c := Cat{}
 // t.Log("Cat say:", c.Say())
 //
 d := Dog{}
 // t.Log("Dog say:", d.Say())

 h := Horse{}

 animals := []Sayer{c, d, h}
 for _, a := range animals {
  t.Log("say:", a.Say())
 }
}

After reading the above code, we define an interface Sayer, which has only one method signature Say. And we have defined a new structure, Horse. Unlike the code without interface, we don't need to use h.Say() to call the Say method of the structure of Horse.

03 interface programming case

In the development of Golang language project, we usually choose open source ORM to make it easier to operate MySQL, but there are many orm in the community. We may encounter the need to replace orm in the later stage of the project. We can use the interface to make ORM invade business code as little as possible to prepare for replacing orm in the future.

type DBOrm interface {
 Insert(param ...interface{})
}

type XormDB struct {
 db *xorm.Session
}
func (x *XormDB) Insert(param ...interface{}) {
 _, err := x.db.Insert(param)
 if err != nil {
  log.Println(err)
 }
}

// type GormDB struct {
//  db *gorm.DB
// }
// 
// func (g *GormDB) Insert(param ...interface{}) {
//  g.db.Create(param)
// }

type User struct {
 orm DBOrm
 Id int64
 Name string
}

func (u *User) DB() DBOrm{
 u.orm = new(XormDB) // Database instance injection interface
 // u.orm = new(GormDB)
 return u.orm
}

func TestOrm(t *testing.T) {
 user1 := new(User)
 user1.Name = "lucy"
 user1.DB().Insert(user1)
}

After reading the above code, we create an interface DBOrm, create two ORM structures, and implement the signature method of the interface DBOrm respectively. The business structure User does not contain an ORM structure, but a DBOrm interface.

04 summary

In this article, we mainly introduce why to use interfaces and the benefits of using interfaces in the development of Golang language project, and prove the benefits of interfaces through example code.

Finally, through the case of using interface to call ORM, this paper introduces the benefits of interface for project development in actual project development.

reference material: https://en.wikipedia.org/wiki/Duck_typing https://stackoverflow.com/questions/39092925/why-are-interfaces-needed-in-golang

Posted on Mon, 29 Nov 2021 21:13:33 -0500 by leocon