其他分享
首页 > 其他分享> > go多态

go多态

作者:互联网

go多态

package main

import (
	"fmt"
)

type Animal interface {
	Speak() string
}

type Dog struct {
}

func (d Dog) Speak() string {
	return "Woof!"
}

type Cat struct {
}

func (c Cat) Speak() string {
	return "Meow!"
}

func main() {
	animals := []Animal{Dog{}, Cat{}}
	for _, animal := range animals {
		fmt.Println(animal.Speak())
	}
}

  

标签:string,Dog,多态,func,go,Cat,type,Speak
来源: https://www.cnblogs.com/hnxxcxg/p/15265863.html