判斷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)

此方法可以在編譯時檢查出相關異常

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