dongyan3562 2016-04-21 03:10
浏览 55
已采纳

为什么Go允许我调用未实现的方法?

Go doesn't seem to enforce the struct adhering to the interface. Why does the following code compile?

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")
}

It seems like this should not compile since SomeMethod is not implemented.go build results in no issues.

Running it results in the runtime error:

> 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
  • 写回答

2条回答 默认 最新

  • dongyan9838 2016-04-21 03:27
    关注

    When a type is embedded (in your example LocalInterface is embedded inside LocalStruct), Go creates a field of the embedded type and promotes its methods to the enclosing type.

    So the following declaration

    type LocalStruct struct {
        LocalInterface
        myOwnField string
    }
    

    is equivalent to

    type LocalStruct struct {
        LocalInterface LocalInterface
        myOwnField string
    }
    
    func (ls *LocalStruct) SomeMethod(s string) error {
        return ls.LocalInterface.SomeMethod(s)
    }
    

    Your program panics with nil pointer dereference because LocalInterface field is nil.

    The following program "fixes" the panic (http://play.golang.org/p/Oc3Mfn6LaL):

    package main
    
    type LocalInterface interface {
        SomeMethod(string) error
    }
    
    type LocalStruct struct {
         LocalInterface
        myOwnField string
    }
    
    type A int
    
    func (a A) SomeMethod(s string) error {
        println(s)
        return nil
    }
    
    func main() {
        var localInterface LocalInterface = &LocalStruct{
            LocalInterface: A(10),
            myOwnField:     "test",
        }
    
        localInterface.SomeMethod("calling some method")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重