多态:就是某一类事物的多种形态。
Go语言中的多态是通过接口类型来实现"多态"。
package main
import "fmt"
// 1.定义接口
type Animal interface {
Eat()
}
type Dog struct {
name string
age int
}
// 2.实现接口方法
func (d Dog) Eat() {
fmt.Println(d.name, "正在吃东西")
}
type Cat struct {
name string
age int
}
// 2.实现接口方法
func (c Cat) Eat() {
fmt.Println(c.name, "正在吃东西")
}
// 3.对象特有方法
func (c Cat) Special() {
fmt.Println(c.name, "特有方法")
}
func main() {
// 1.利用接口类型保存实现了所有接口方法的对象
var a Animal
a = Dog{"旺财", 18}
// 2.利用接口类型调用对象中实现的方法
a.Eat()
a = Cat{"喵喵", 18}
a.Eat()
// 3.利用接口类型调用对象特有的方法
//a.Special() // 接口类型只能调用接口中声明的方法, 不能调用对象特有方法
if cat, ok := a.(Cat); ok {
cat.Special() // 只有对象本身才能调用对象的特有方法
}
}
多态优点:
空接口可以表示任何类型(类似Java的object)
通过断言来将空接口转换为指定类型(类似于x.(T),其中x是一个接口类型的表达式、T是一个类型)
package empty_interface
import (
"fmt"
"testing"
)
func DoSomething(p interface{}) { // 传入的是个空接口
if i, ok := p.(int); ok { // 断言判断
fmt.Println("Integer: ", i)
return
}
if s, ok := p.(string); ok {
fmt.Println("string: ", s)
return
}
fmt.Println("Unknow Type.")
}
func TestEmptyInterfaceAssertion(t *testing.T) {
DoSomething(10)
DoSomething("10")
}
以上方法有点繁琐,最好使用switch结构
package empty_interface
import (
"fmt"
"testing"
)
func DoSomething2(p interface{}) {
switch v := p.(type) {
case int:
fmt.Println("Integer: ", v)
case string:
fmt.Println("string: ", v)
default:
fmt.Println("Unknow Type.")
}
}
func TestEmptyInterfaceAssertion2(t *testing.T) {
DoSomething2(10)
DoSomething2("10")
}
type Reader interface{
Read(p []byte) (n int, err error)
}
type Writer interface{
Writer(p []byte) (n int, err error)
}
type ReadWriter interface {
Reader
Writer
}
type StoreData(reader Reader) error {
...
}