golang 斷言判斷

package main

import (
	"fmt"
)
type Ifly interface{
	Fly()
}
type Name interface{
	Data()
}
type Demo struct {
}

func (d Demo)Data()  {
	fmt.Println("OK")
}
func (d Demo)Fly()  {
	fmt.Println("fly")
}

func main() {
	var s Name= Demo{}
	// 斷言判斷 s 是否 Name 接口
	if f,ok := s.(Name);ok {
		fmt.Println(f)
		fmt.Println(s)
		fmt.Println("N是 Name 接口的實現")
	}else {
		fmt.Println("N不是 Name 接口的實現")
	}

	if f,ok := s.(Ifly);ok {
		fmt.Println(f)
		fmt.Println(s)
		fmt.Println("N是 Ifly 接口的實現")
	}else {
		fmt.Println("N不是 Ifly  接口的實現")
	}
}
相關文章
相關標籤/搜索