Go 似乎没有强制遵守接口的结构。为什么下面的代码会编译?
package main
type LocalInterface interface {
SomeMethod(string) error
SomeOtherMethod(string) error
}
type LocalStruct struct {
LocalInterface
myOwnField string
}
func main() {
var localInterface LocalInterface = &LocalStruct{myOwnField:"test"}
localInterface.SomeMethod("calling some method")
}
似乎这不应该编译,因为SomeMethod没有实现。go build结果没有问题。
运行它会导致运行时错误:
> go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x20 pc=0x4013b0]
goroutine 1 [running]:
panic(0x460760, 0xc08200a090)
C:/Go/src/runtime/panic.go:464 +0x3f4
main.(*LocalStruct).SomeMethod(0xc0820064e0, 0x47bf30, 0x13, 0x0, 0x0)
<autogenerated>:3 +0x70
main.main()
C:/Users/kdeenanauth/Documents/git/go/src/gitlab.com/kdeenanauth/structTest/main.go:16 +0x98
exit status 2
森栏
万千封印
相关分类