package main
type A interface {
GetName() string
}
type B struct {
A
}
func (this *B) Func1() {
this.GetName()
}
type C struct {
B
}
func (this *C) GetName() string {
return "hello"
}
func main() {
var c = new(C)
c.GetName()
c.Func1()
}
https://play.golang.org/p/1X7yiQeie8F
我的问题:
c.Func1() 将导致:
panic :运行时错误:无效的内存地址或零指针取消引用
我的情况是:
用户需要实现A的一些基本接口(interface),然后用户才能使用B的成员函数。我希望复杂的代码封装到B的成员函数中,用户只需要提供基本信息。
如何实现这个目标?
最佳答案
我看到你的代码永远循环 GetName
重复调用
你可以看到我的代码
package main
import "fmt"
type A interface {
GetName() string
}
type B struct {
A
}
func (this *B) Func1() {
}
type C struct {
B
}
func (this *C) GetName() string {
return "hello"
}
func main() {
var c = new(C)
fmt.Println(c.GetName())
}
https://play.golang.org/p/PaFd-BS9sdP
关于go - 如何在golang中结合接口(interface)和结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59211993/