官术网_书友最值得收藏!

Interfaces

An interface is a set of methods. We can define an interface by listing out the methods it's expected to support. For example, consider the following interface:

var a interface {
check()
}

Here we are defining a to be a variable that has the type interface{ check() }. What on earth does that mean?

It means that you can put any value into a, as long as the value has a type that has a method called check().

Why is this valuable? It's valuable when considering multiple types that do similar things. Consider the following:

 type complicatedEmail struct {...}

func (e complicatedEmail) check() {...}
func (e complicatedEmail) send(a string) {...}

type simpleEmail string

func (e simpleEmail) check() {...}
func (e simpleEmail) send(a string) {...}

Now we want to write a function do, which does two things:

  • Check that an email address is correct
  • Send "Hello World" to the email

You would need two do functions:

func doC(a complicatedEmail) {
a.check()
a.send("Hello World")
}

func doS(a simpleEmail) {
a.check()
a.send("Hello World")
}

Instead, if that's all the bodies of the functions are, we may opt to do this:

func do(a interface{
check()
send(a string)
}) {
a.check()
a.send("Hello World")
}

This is quite hard to read. So let's give the interface a name:

type checkSender interface{
check()
send(a string)
}

Then we can simply redefine do to be the following:

func do(a checkSender) {
a.check()
a.send("Hello World")
}

A note on naming interfaces in Go. It is customary to name interfaces with a -er suffix. If a type implements check(), then the interface name should be called checker. This encourages the interfaces to be small. An interface should only define a small number of methods—larger interfaces are signs of poor program design.

主站蜘蛛池模板: 建水县| 越西县| 五峰| 叙永县| 广丰县| 井研县| 唐海县| 卢氏县| 得荣县| 宣威市| 游戏| 荣成市| 新乡县| 林州市| 林州市| 宜昌市| 饶平县| 镇平县| 屏南县| 五华县| 洪江市| 菏泽市| 婺源县| 佛坪县| 山阳县| 姚安县| 竹溪县| 壶关县| 长白| 丰顺县| 正镶白旗| 沁水县| 武定县| 兴化市| 曲沃县| 镇沅| 玉门市| 嘉祥县| 高安市| 桃园市| 泌阳县|