Harlam
Harlam

Reputation: 438

Polymorphism in Golang

It's simple example what I want:

I have object of B and use function step1 from struct A (common functionality). I need to redefine function step2 for B which runs inside A.

package main

import "fmt"

type A struct {}

func (a *A) step1() {
    a.step2();
}

func (a *A) step2 () {
   fmt.Println("get A");
}


type B struct {
   A
}

func (b *B) step2 () {
   fmt.Println("get B");
}

func main() {
    obj := B{}
    obj.step1() 
}

How can I do it?

// maybe 
func step1(a *A) {
   self.step2(a);
}

Upvotes: 1

Views: 1408

Answers (1)

Nick Craig-Wood
Nick Craig-Wood

Reputation: 54079

Go doesn't do polymorphism. You have to recast what you want to do in terms of interfaces, and functions (not methods) that take those interfaces.

So think what interface does each object need to satisfy, then what functions you need to work on that interface. There are lots of great examples in the go standard library, eg io.Reader, io.Writer and the functions which work on those, eg io.Copy.

Here is my attempt to recast your example into that style. It doesn't make a lot of sense, but hopefully it will give you something to work on.

package main

import "fmt"

type A struct {
}

type steps interface {
    step1()
    step2()
}

func (a *A) step1() {
    fmt.Println("step1 A")
}

func (a *A) step2() {
    fmt.Println("get A")
}

type B struct {
    A
}

func (b *B) step2() {
    fmt.Println("get B")
}

func step1(f steps) {
    f.step1()
    f.step2()
}

func main() {
    obj := B{}
    step1(&obj)
}

Upvotes: 7

Related Questions