简介

Go 语言不是一种 “传统” 的面向对象编程语言:它里面没有类和继承的概念。
但是 Go 语言里有非常灵活的 接口 概念,通过它可以实现很多面向对象的特性。接口提供了一种方式来 说明 对象的行为:如果谁能搞定这件事,它就可以用在这儿。
接口定义了一组方法(方法集),但是这些方法不包含(实现)代码:它们没有被实现(它们是抽象的)。接口里也不能包含变量。

通过如下格式定义接口:

type Namer interface {Method1(param_list) return_typeMethod2(param_list) return_type...
}

例子

package mainimport "fmt"type Shaper interface {Area() float32
}type Square struct {side float32
}func (sq *Square) Area() float32 {return sq.side * sq.side
}func main() {sq1 := new(Square)sq1.side = 5var areaIntf ShaperareaIntf = sq1fmt.Printf("The square has area: %f\n", areaIntf.Area())
}

结果

The square has area: 25.000000

上面的程序定义了一个结构体 Square 和一个接口 Shaper,接口有一个方法 Area()。
在 main() 方法中创建了一个 Square 的实例。在主程序外边定义了一个接收者类型是 Square 方法的 Area(),用来计算正方形的面积:结构体 Square 实现了接口 Shaper 。
所以可以将一个 Square 类型的变量赋值给一个接口类型的变量:areaIntf = sq1 。
现在接口变量包含一个指向 Square 变量的引用,通过它可以调用 Square 上的方法 Area()。当然也可以直接在 Square 的实例上调用此方法,但是在接口实例上调用此方法更令人兴奋,它使此方法更具有一般性。接口变量里包含了接收者实例的值和指向对应方法表的指针。
这是 多态 的 Go 版本,多态是面向对象编程中一个广为人知的概念:根据当前的类型选择正确的方法,或者说:同一种类型在不同的实例上似乎表现出不同的行为。

如果 Square 没有实现 Area() 方法,编译器将会给出清晰的错误信息:

cannot use sq1 (type *Square) as type Shaper in assignment:
*Square does not implement Shaper (missing Area method)

如果 Shaper 有另外一个方法 Perimeter(),但是Square 没有实现它,即使没有人在 Square 实例上调用这个方法,编译器也会给出上面同样的错误。

扩展上面的例子

扩展一下上面的例子,类型 Rectangle 也实现了 Shaper 接口。接着创建一个 Shaper 类型的数组,迭代它的每一个元素并在上面调用 Area() 方法,以此来展示多态行为:

package mainimport "fmt"type Shaper interface {Area() float32
}type Square struct {side float32
}func (sq *Square) Area() float32 {return sq.side * sq.side
}type Rectangle struct {length, width float32
}func (r Rectangle) Area() float32 {return r.length * r.width
}func main() {r := Rectangle{5, 3} // Area() of Rectangle needs a valueq := &Square{5}      // Area() of Square needs a pointer// shapes := []Shaper{Shaper(r), Shaper(q)}// or shortershapes := []Shaper{r, q}fmt.Println("Looping through shapes for area ...")for n, _ := range shapes {fmt.Println("Shape details: ", shapes[n])fmt.Println("Area of this shape is: ", shapes[n].Area())}
}

结果

Looping through shapes for area ...
Shape details:  {5 3}
Area of this shape is:  15
Shape details:  &{5}
Area of this shape is:  25

在调用 shapes[n].Area()) 这个时,只知道 shapes[n] 是一个 Shaper 对象,最后它摇身一变成为了一个 Square 或 Rectangle 对象,并且表现出了相对应的行为。

更具体的例子

有两个类型 stockPosition 和 car,它们都有一个 getValue() 方法,我们可以定义一个具有此方法的接口 valuable。接着定义一个使用 valuable 类型作为参数的函数 showValue(),所有实现了 valuable 接口的类型都可以用这个函数。

package mainimport "fmt"type stockPosition struct {ticker     stringsharePrice float32count      float32
}/* method to determine the value of a stock position */
func (s stockPosition) getValue() float32 {return s.sharePrice * s.count
}type car struct {make  stringmodel stringprice float32
}/* method to determine the value of a car */
func (c car) getValue() float32 {return c.price
}/* contract that defines different things that have value */
type valuable interface {getValue() float32
}func showValue(asset valuable) {fmt.Printf("Value of the asset is %f\n", asset.getValue())
}func main() {var o valuable = stockPosition{"GOOG", 577.20, 4}showValue(o)o = car{"BMW", "M3", 66500}showValue(o)
}

结果

Value of the asset is 2308.800049
Value of the asset is 66500.000000

转载地址

https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/11.1.md