判断Golang中接口是否实现

判断Golang中接口是否实现

使用声明变量的语法实现

var _ 接口 = (*实现接口的结构)(nil)
package main

import "fmt"

type A interface {
	Hi()
}

type a struct {
}

type b struct {
}

func (i a) Hi() {
	fmt.Println("Hi A.")
}

var (
	_ A = (*a)(nil)
	_ A = (*b)(nil)
)

func main() {

}

上述代码在编译go build时会报以下错误:

# command-line-arguments
./b.go:21:2: cannot use (*b)(nil) (type *b) as type A in assignment:
        *b does not implement A (missing Hi method)

此方法可以在编译时检查出相关异常

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章