Golang Method Override

Interfaces are named collections of method signatures:
see: https://gobyexample.com/interfaces
and: http://www.golangbootcamp.com/book/interfaces
so it is better not to use in such OOP way.


what you asking is not Golang idiomatic
but possible (2 ways):

this is what you need (working sample code):

package main

import "fmt"

type Base struct {
}

func (base *Base) Get() string {
    return "base"
}

type Getter interface {
    Get() string
}

func (base *Base) GetName(getter Getter) string {
    if g, ok := getter.(Getter); ok {
        return g.Get()
    } else {
        return base.Get()
    }
}

// user code :
type Sub struct {
    Base
}

func (t *Sub) Get() string {
    return "Sub"
}
func (t *Sub) GetName() string {
    return t.Base.GetName(t)
}

func main() {
    userType := Sub{}
    fmt.Println(userType.GetName()) // user string
}

output:

Sub

as you see one initialization code must be done in user code:

func (t *Sub) GetName() string {
    return t.Base.GetName(t)
}

also this works:

package main

import "fmt"

type Getter interface {
    Get() string
}

type Base struct {
    Getter
}

func (base *Base) Get() string {
    return "base"
}

func (base *Base) GetName() string {
    return base.Getter.Get()
}

// user code :
type Sub struct {
    Base
}

func (t *Sub) Get() string {
    return "Sub"
}
func New() *Sub {
    userType := &Sub{}
    userType.Getter = interface{}(userType).(Getter)
    return userType
}

func main() {
    userType := New()
    fmt.Println(userType.GetName()) // user string
}

output:

Sub

as you see one initialization code must be done in user code:

userType.Getter = interface{}(userType).(Getter)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)