M
M
midia212022-02-21 13:21:23
go
midia21, 2022-02-21 13:21:23

Why are "reference" methods needed and why don't they satisfy interfaces?

I often see that function parameters, structure properties in Go are passed as links. In general, this is understandable - I read that it saves memory + you can check for nil to check for an untransmitted parameter. However, it is a little confusing when methods are tied to a structure through "*":

type Speaker interface {
  Speak()
}

type Human struct {}

func (h *Human) Speak() {

}


To clarify: why write func (h *Human) if you can write func (h Human)?

Additional question: it is a little unclear why in this example Human will not satisfy the Speaker interface (error: missing method Speak (Speak has pointer receiver))? However, if you remove the method binding by reference, everything is fine. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2022-02-21
@midia21

func (h *Human) Speak() {

}

If you look at the internals of the language, then a method is essentially a regular function whose first parameter is the receiver (the object on which the method is called). That is, the compiler will turn this code into
func Speak(h *Human) {

}

Accordingly, when calling the method in the case of *Human, the structure will be passed by pointer, and in the case of Human, by value, with all the consequences.
As for the error about the mismatch with the interface, then it must be taken into account that if the structure has methods defined through a pointer, then the pointer to this structure will correspond to the interface: https://go.dev/play/p/o7EsGmeYSRS
If without a pointer, then The structure itself will correspond to the interface: https://go.dev/play/p/oTsXP4DXaMJ
But both cannot be determined at the same time.

W
WinPooh32, 2022-02-21
@WinPooh32

*Human and Human are two completely different data types.
This means that the implementation for interfaces for each type must be done separately.
*Human - a pointer to a Human value .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question