Re: [go-nuts] Struct overloading method issue

2017-09-02 Thread Jesse McNelis
On Sat, Sep 2, 2017 at 12:50 AM, BeaT Adrian  wrote:
> Hello, I ran into a strange scenario and I wanted to know if there is a
> better solution for it
>
> type A struct{}
>
> func (a *A) private() {}
> func (a *A) Public() {
>a.private()
> }
>
> type B struct {A}
>
> func (b *B) private() {}
>
> bi := B{}
> b.Public() //calls the A.Private
>

Go doesn't do inheritance only composition with method forwarding.
Trying to do it will make you sad.

The general solution to sharing code between two types is to write a
function that takes a common interface that both A and B implement.

eg.

type Privater interface {
  private()
}

func Public(p Privator){
p.private()
}

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[go-nuts] Struct overloading method issue

2017-09-01 Thread BeaT Adrian
Hello, I ran into a strange scenario and I wanted to know if there is a 
better solution for it

type A struct{}

func (a *A) private() {}
func (a *A) Public() {
   a.private()
}

type B struct {A}

func (b *B) private() {}

bi := B{}
b.Public() //calls the A.Private



I just want to rewrite a small part of the algorithm.
As a workaround I used composition, but in a weird way
type A struct {
 private
}

func (a *A) Public() {
   if a.private == nil {
 //set private for A
   }
   a.private
}
type B struct {A}
func (b *B) Public() {
 if b.private == nil {
  //set private for B
 }
}

 

Other solutions I tried were not effective (how to detect in inner A 
function that it's a B now, and should use other algorithm).

Thanks!



-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.