測試介面實現

由於 Go 使用隱式介面實現,如果你的結構沒有實現你打算實現的介面,則不會出現編譯時錯誤。你可以使用型別轉換顯式測試實現:type MyInterface interface {Thing()}

type MyImplementer struct {}

func (m MyImplementer) Thing() {
    fmt.Println("Huzzah!")
}

// Interface is implemented, no error. Variable name _ causes value to be ignored.
var _ MyInterface = (*MyImplementer)nil

type MyNonImplementer struct {}

// Compile-time error - cannot case because interface is not implemented.
var _ MyInterface = (*MyNonImplementer)nil