package main
import "fmt"
type animal interface {
speak() }
type dog struct{}
type cat struct{}
func (dg dog) speak() {
fmt.Println("emmmm,dog dog dog")
}
func (ct cat) speak() {
fmt.Println("miao miao miao ??")
}
func call(am animal) {
am.speak() }
func main() {
var dg, ct animal
dg = dog{}
ct = cat{}
call(dg) call(ct) }
package main
import "fmt"
//多态
type animal interface {
say()
}
type father struct {
name string
}
type son struct {
father
}
func(f father)say() {
fmt.Println(f.name + "正在说话~")
}
func(s son)say() {
fmt.Println(s.name + "正在插嘴~~")
}
func main() {
var f animal = father{name:"父亲"}
var s animal = son{father{"儿子"}}
f.say()
s.say()
} 通过实现接口实现多态
package main
import "fmt"
type Int int
type Float float32
type Printer interface {
printInt()
}
func (m Int)printInt() {
fmt.Println(m)
}
func (f Float) printInt() {
fmt.Printf("%d",int(f))
}
func main() {
var a Printer= Int(5)
var b Printer= Float(5.5)
a.printInt()
b.printInt()
}