判断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)
此方法可以在编译时检查出相关异常