type Animal interface {
Run()
Say()
}
type Horse struct {
Name string
}
type Dog struct {
Name string
}
func (h *Horse) Run(){
fmt.Println("Horse Run")
}
func (h *Horse) Say(){
fmt.Println("Horse Say")
}
func (d *Dog) Run(){
fmt.Println("Dog Run")
}
func (d *Dog) Say(){
fmt.Println("Dog Say")
}
func animalAction(animal Animal){
animal.Run()
animal.Say()
}
func main(){
horse := &Horse{
"Horse",
}
dog := &Dog{
"dog",
}
fish := &Fish{
"fish",
}
animalAction(horse) // Horse Run Horse Say
animalAction(dog)// Dog Run Dog Say
}
代码解释
我们可以通过变量后面 . (类型)的语法对变量进行断言
func demo1(){
var i interface{}
var str string
i = "adf"
str = i.(string)
fmt.Print(str) // abc
}
func demo2(){
var i interface{}
var number int
i = 123
number = i.(int)
fmt.Print(number) // 123
}
func demo3(i interface{}){
value1 ,ok1 := i.(string)
if ok1 {
fmt.Printf("i is string,value:%s\n",value1)
}
value2 ,ok2 := i.(int)
if ok2 {
fmt.Printf("i is int,value:%d\n",value2)
}
}
func main(){
demo3(1) // i is int,value:1
demo3("abc") // i is string,value:abc
}
如果觉得上面那种 if 判断多个类型的时候很麻烦,我们可以使用 switch i.(type) 语法来判断多个类型。
func demo4(i interface{}){
switch i.(type) {
case int:
fmt.Println("is int")
case string:
fmt.Println("is string")
case bool:
fmt.Println("is bool")
}
}
func main(){
demo4(1)//is int
demo4("abc")// is string
demo4(true)//is bool
}