【问题标题】:How to known a function of a interface is not realized? [duplicate]如何知道某个接口的功能没有实现? [复制]
【发布时间】:2020-01-03 06:14:53
【问题描述】:

我刚刚在 Go 中尝试了以下代码。

package main

type inter interface {
    aaa() int
}

type impl struct {
    inter
}

func main() {
    var a inter
    a = impl{}
    // how to check the function for interface `inter` is not realized?
    a.aaa()
}

可以是go buildgo run。但会收到如下恐慌:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x8972c]

goroutine 1 [running]:
main.(*impl).aaa(0x40c018, 0x41a788, 0xb2ae0, 0x40c018)
    <autogenerated>:1 +0x2c
main.main()
    /tmp/sandbox029518300/prog.go:15 +0x60

我怎么知道a.aaa()没有实现。

【问题讨论】:

  • 但是a的类型是inter。它没有属性inter

标签: go panic


【解决方案1】:

变量a的类型是inter,一个接口,它指向一个implimpl 结构体中嵌入了 inter 接口。这意味着impl.aaa() 存在,这实际上意味着impl.inter.aaa()。但是在您的代码中,impl.inter 为零。为了更清楚:

b:=impl{}
var a inter
a=b
a.aaa() // this will call b.inter.aaa(), but b.inter is nil

【讨论】:

  • 感谢您的回答。因此,避免这种情况恐慌的唯一方法是检查Typeinter?
  • @lzmhhh123,不,你只需要正确初始化你的结构。不要让 inter 字段为零。
猜你喜欢
  • 1970-01-01
  • 2021-01-14
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
相关资源
最近更新 更多