多态是 C++ 这种语言中的概念,是指对不同的子类对象运行自己定义的方法。在 Go 语言中没有类的概念,但仍然可以使用 struct + interface 来模拟实现类的功能。下面这个例子演示如何使用 Go 来模拟 C++ 中的多态行为。
1package main 2 3import "fmt" 4 5// 首先定义了一个 Shaper 接口,它有一个 Area() 方法 6type Shaper interface { 7 Area() float32 8} 9 10// 定义 Square 结构体 11type Square struct { 12 side float32 13} 14 15// 定义一个方法,方法的接受者是 Square* 的对象。 16// 可以看作是 Square 的一个成员函数,而这个方法又是实现 Shaper 接口的。 17// 类似于 C++ 中继承并实现 Shaper。 18func (sq *Square) Area() float32 { 19 return sq.side * sq.side 20} 21 22// 定义 Rectangel 结构体 23type Rectangle struct { 24 length, width float32 25} 26 27// 定义一个方法,方法的接受者是 Rectangle 的对象。 28// 可以看作是 Rectangle 的一个成员函数,而这个方法又是实现 Shaper 接口的。 29// 类似于 C++ 中继承并实现 Shaper。 30func (r Rectangle) Area() float32 { 31 return r.length * r.width 32} 33 34func main() { 35 rect := Rectangle{5, 3} 36 squa := &Square{5} 37 38 shapes := []Shaper{rect, squa} 39 fmt.Println("Looping through shapes for area...") 40 41 for n, _:= range shapes { 42 fmt.Println("Shape details: ", shapes[n]) 43 fmt.Println("Area of this shape is: ", shapes[n].Area()) 44 } 45}
最后 shapers 调用 Area() 方法时,调用了各自实现的逻辑。这就模拟出了多态。