T
T
Twindo2016-05-24 18:30:29
go
Twindo, 2016-05-24 18:30:29

Is there an alternative to overriding methods in Go?

There is the following code:

package main

import (
  "fmt"
)

//
// Inteface
//

type X interface {
  Print()
}

//
// Impl A
//

type A struct {
}

func (a *A) Print() {
  fmt.Println(a.Get())
}

func (a *A) Get() string {
  return "A"
}

//
// Impl B
//

type B struct {
  *A
}

func (b *B) Get() string {
  return "B"
}

//
// Main
//

func main() {
  x := &B{A: &A{}}
  x.Print() 
}

What are some ways to have x.Print() Print "B" to the screen?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2016-05-24
@Twindo

Go is supposed to have this style:
https://play.golang.org/p/uFA4rWeHn4

package main

import (
  "fmt"
)

//
// Inteface
//

type Gettable interface {
  Get() string
}

//
// Impl A
//

type A struct {
}

func (a *A) Get() string {
  return "A"
}

//
// Impl B
//

type B struct {
}

func (b *B) Get() string {
  return "B"
}

//
// Main
//

func main() {
  a := A{}
  b := B{}
  PrintSomeStuff(&a)
  PrintSomeStuff(&b)
}

func PrintSomeStuff(obj Gettable) {
  fmt.Println(obj.Get())
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question