-1

Look at this code. Everything works fine:

type moninterface2 interface {
    methode_commune(a,b int) int
}

type classe1 struct {
    a, b int
}

type classe2 struct {
    c, d int
}

func (r classe1) methode_commune(a,b int) int {
    return a+b
}

func (r classe2) methode_commune(a,b int) int {
    return a*b
}

func fonctiontest(param moninterface2) {
    ret := param.methode_commune(2,3)
    fmt.Println(ret)
}

But if I declare methode_commune like this:

func (r *classe1) methode_commune(a,b int) int 
func (r *classe2) methode_commune(a,b int) int 

Go does not consider classe1 and classe2 implements moninterface2 and the code does not compile. I do not understand why.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Bob5421
  • 7,757
  • 14
  • 81
  • 175
  • What is the compilation error you receive? It probably tells you why. – Jonathan Hall Nov 24 '17 at 10:40
  • It does compile for me. Can you give more detail? https://play.golang.org/p/hUCFWu5tl1 – Wendy Adi Nov 24 '17 at 10:49
  • Make sure to pass a pointer instead of just a value. E.g. `fonctiontest(&classe1{})` is ok, `fonctiontest(classe1{})` is **not** ok. – mkopriva Nov 24 '17 at 10:55
  • Check out this question: [Go, X does not implement Y (… method has a pointer receiver)](https://stackoverflow.com/questions/40823315/go-x-does-not-implement-y-method-has-a-pointer-receiver/40824044#40824044) – icza Nov 24 '17 at 11:14

1 Answers1

1

Go does not consider classe1 and classe2 implements moninterface2 and the code does not compile. I do not understand why.

Because after you change the working code to this:

func (r *classe1) methode_commune(a,b int) int 
func (r *classe2) methode_commune(a,b int) int 

the two types, classe1 and classe2, do not implement the interface anymore, instead the two types *classe1 and *classe2 implement the moninterface2 interface.

T and *T are not one and the same type.

Therefore to make the code compile you'll have to pass a pointer to classe1 or classe2 whereever the moninterface2 interface is expected. E.g. fonctiontest(&classe1{}).

mkopriva
  • 35,176
  • 4
  • 57
  • 71