简体   繁体   中英

How to combine an interface and struct in golang?

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

My question: c.Func1() will lead to:
panic: runtime error: invalid memory address or nil pointer dereference


My scenario is: user needs to implement some basic interfaces of A, and then user can use the member function of B. I hope that complicate codes are encapsulated into the member function of B, and user just need to provide basic infos.
How to achieve this goal?

I see your code looping forever GetName calling duplicate

you can see my code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM