有时候,有些方法由于错误的修改或者落掉了,但是编译器提示信息不太强烈,非常不太好找具体哪个方法没有实现,也很难寻找定位具体的方法或者接口的不一致导致出错。
首先分析一下
由于golang的interface使用很灵活,不需要显示的实现接口interface的方法, 有点动态化的感觉,
缺点:如果没有实现interface的方法,强行转换成interface,运行时候异常报错
解决办法:在编译的时候就把这种错误抛出来,上代码:
package main
import (
"fmt"
)
type value interface {
Show()
}
type test_value struct{}
// func (value *test_value) Show() { fmt.Printf("test \n") }
var _ value = new(test_value) // 使用类似方法处理,编译的时候会报错
func main() {
}
// -------------------------------- Error Msg -------------------------------- //
./test.go:18: cannot use new(test_value) (type *test_value) as type value in assignment:
*test_value does not implement value (missing Show method)
// 如果把接口的方法注释掉,编译的时候就会报错
// ------------------- 总结来说 ---------------
type T struct{}
var _ I = T{}
其中 I为interface
// 上面用来判断 type T是否实现了I,用作类型断言,如果T没有实现接口I,则编译错误.