判斷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)
此方法可以在編譯時檢查出相關異常