如何在golang中结合使用接口和结构?

问题描述 投票:-3回答:1
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()将导致:紧急:运行时错误:无效的内存地址或nil指针取消引用

我的情况是:用户需要实现A的一些基本接口,然后用户才能使用B的成员函数。我希望将复杂的代码封装到B的成员函数中,并且用户只需要提供基本信息即可。如何实现这个目标?

go inheritance interface encapsulation
1个回答
0
投票

我看到您的代码永远循环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
© www.soinside.com 2019 - 2024. All rights reserved.