Home > Blockchain >  Understanding conflicting Interfaces
Understanding conflicting Interfaces

Time:02-11

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?

CodePudding user response:

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

CodePudding user response:

Your interfaces do not conflict with each other; interfaces do not conflict. They can be redundant with each other as they describe the same thing, but that doesn't create a conflict nor any other tangible problem.

As for which interface is structure using: neither. Concrete types such as structs don't use interfaces, they implement them. Implementing of an interface is implicit and automatic. It's just a statement of fact, not a mechanism (until you explicitly use it as such). Further, neither interface is used to any extent in your program. Your variable is a structure and is being used as a structure. It could be used as either InterfaceA or InterfaceB, or both of them at different times, but you are doing no such thing in this example.

See Burak's answer for how you could use the structure value through the interfaces.

  • Related