Go语言没有类和继承的概念,但是接口的存在使得它可以实现很多面向对象的特性。接口定义了一些方法,但是这些方法不包含实现的代码。也就是说这些代码没有被实现(抽象的方法)。同时接口里面也不包含变量。

看一个简单的接口定义:

type inf interface {
    Method1(param)
    Method2(param)
}

  在go语言中接口一般包含0-3个方法。类型(如结构体)实现了接口中的方法,就是实现了接口,实现了接口类型的结构体变量可以赋值给接口类型的变量,直接看一个例子帮助理解:

package main
import (
    "fmt"
)
type stockPosition struct {
    ticker     string
    sharePrice float32
    count      float32
}
func (s stockPosition) getValue() float32 {
    return s.sharePrice * s.count
}
 
type valueable interface {
    getValue() float32
}
func showValue(asset valueable) {
    fmt.Printf("value of the asset is %f\n", asset.getValue())
}
func main() {
    var o valueable
    o = stockPosition{"GOOG", 577.20, 4}
    showValue(o)
 
}
Output:value of the asset is 2308.800049

接口o,然后将实现了这个接口的结构体赋值给了o。Golang的接口不需要显示的声明,好处有:

1.在接口实现过程中只要关心自己要提供哪些方法就行,不用纠结其他。

2.不用担心其他模块定义过类似的接口,只要关心自己有什么需求,然后按照需求去定义就行。

继续看。我们稍微加点料,代码添加几行如下:

package main
import (
    "fmt"
)
type stockPosition struct {
    ticker     string
    sharePrice float32
    count      float32
}
func (s stockPosition) getValue() float32 {
    return s.sharePrice * s.count
}
type f float32
func (s f) getValue() float32 {
    return 0.1
}
type valueable interface {
    getValue() float32
}
func showValue(asset valueable) {
    fmt.Printf("value of the asset is %f\n", asset.getValue())
}
func main() {
    var o valueable
    o = stockPosition{"GOOG", 577.20, 4}
    showValue(o)
    var t f
    o = t
    showValue(o)
}
Output:
value of the asset is 2308.800049
value of the asset is 0.100000

  我们定义了一个f,然后实现了getValue方法,其赋值给o,再调用valueable类型的接口才可以调用的showValue打印值。也就是说所有实现了valueable接口的类型都可以调用这个函数。

  总结下,golang不支持面向对象的编程思想(没有类,没有继承),而要实现多态就完全需要接口了。接口就是一组方法的集合,它对外隐藏了方法的实现。只要一个类型A实现了接口中的方法,这个接口的变量o就可以接受类型A的变量,其他的变量也实现了的话,也o也可以接受其他变量。