您使用了该
UniversalError()方法,但是没有将其添加到“定义”接口中,因此请执行以下操作:
type UniversalError interface { CommonError1 UniversalError()}而你想
Error3成为一个
UniversalError。对于
Error3成为一个
UniversalError,它必须实现所有的方法:
UniversalError()和
CommonError1()。因此,您必须同时添加这两种方法:
func (Error3) CommonError1() {}func (Error3) UniversalError() {}经过这些更改,输出将是(在Go Playground上尝试):
**** Types *****Error belongs to an unidentified typeError belongs to an unidentified typeCommonError1 found, but Does not belong to Error1 or Error2
提示: 如果要在编译时保证某些具体类型实现某些接口,请使用空白变量声明,如下所示:
var _ UniversalError = Error3{}上面的声明将的值分配给
Error3type的变量
UniversalError。不应该
Error3满足
UniversalError,您会得到一个编译时错误。上面的声明将不会引入新变量,因为使用了空白标识符,这只是编译时检查。
如果要删除该
Error3.CommonError1()方法:
//func (Error3) CommonError1() {}func (Error3) UniversalError() {}然后,您将立即收到编译时错误:
./prog.go:49:5: cannot use Error3 literal (type Error3) as type UniversalError in assignment: Error3 does not implement UniversalError (missing CommonError1 method)



