Answer the question
In order to leave comments, you need to log in
Why do we need interfaces in golang?
The question may seem silly. I'm learning golang recently. Naturally read articles, but did not understand. What exactly can I do with interfaces and what can't I do without them (or at great expense)?
It’s just that I haven’t used them in the code yet and I want to figure out when they should be used.
Answer the question
In order to leave comments, you need to log in
I myself was looking for an answer to this question. And inspired by the example with light bulbs, I figured it out)
Let it lie here for posterity
package main
import "fmt"
type LampDiode struct{}
func (l *LampDiode) ScrewOn() string {
return "Lamp 1"
}
type LampIncandescent struct{}
func (l *LampIncandescent) ScrewOn() string {
return "Lamp 2"
}
type Lamp interface {
ScrewOn() string
}
func Chandelier(l Lamp) {
fmt.Println(l.ScrewOn())
}
func main() {
var l1 Lamp
l1 = new(LampDiode)
Chandelier(l1)
var l2 Lamp
l2 = new(LampIncandescent)
Chandelier(l2)
}
For example, I am writing a package for myself, in which there is a function that must take a pointer to some structure, and the structure must have certain methods that must be called inside the function. And the user of the package in his program must write his own structures and pass them to the function described in the package. Using the interface (or specifying it as the type of the passed one) inside the function, we check the presence of the necessary methods for the passed structure.
Let me give you an example from reality: you have a chandelier, a lot of light bulbs fit there (diode, incandescent, halogen, whatever you want in general ...) and all this is because the base is identical.
The interface makes it possible to use different implementations of structures, but with a single interface (a bit of tautology for the god of tautology).
---
If all plinths were different: you would have to change either the chandelier or the light bulbs.
If you do not use interfaces, you will not be able to use other structures, even if they are completely identical.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question