Understanding conflicting Interfaces

Issue

I am trying to understand the interface concept.
The following is my test code:

package main

import "fmt"

//interface
type InterfaceA interface {
    A() string
}

//interface
type InterfaceB interface {
    A() string
}

//user defined type structure
type structure struct {
    a string
}

//implementing A(), but which A() ?
func (strt structure) A() string {
    return strt.a
}

func main() {
    fmt.Println("Start")
    variable := structure{"hello"}
    fmt.Println(variable.A())
}

As per the documentation, I understand that there is no explicit mention of "Implements" like in other languages. But when I call variable.A() which interface is my type structure using? InterfaceA or InterfaceB ? Plus, am I actually implementing the interface properly?

Solution

When you call variable.A(), you are not using any interfaces. You are calling a method of the type structure.

You can call the same method using an interface:

variable := structure{"hello"}
var ia InterfaceA
ia=variable
ia.A() // This calls variable.A
var ib InterfaceB
ib=variable
ib.A() // This also calls variable.A

Answered By – Burak Serdar

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.