Home >Backend Development >Golang >Value vs. Pointer Receivers in Go Interfaces: When Does Interface Assignment Fail?
Understanding Go Structure Methods and Interface Implementation
In Go, methods that fulfill an interface can be categorized into two types: methods with value receivers and methods with pointer receivers. When implementing interfaces, however, the assignability of values to the interface differs from direct struct method calls.
Consider the provided code snippet:
type greeter interface { hello() goodbye() }
The greeter interface defines two methods, hello and goodbye.
type tourGuide struct { name string }
The tourGuide struct implements the greeter interface.
func (t tourGuide) hello() { fmt.Println("Hello", t.name) }
Method hello has a value receiver, which allows for direct method invocation using a variable of type tourGuide.
func (t *tourGuide) goodbye() { fmt.Println("Goodbye", t.name) }
Method goodbye, on the other hand, has a pointer receiver, which requires a pointer variable to invoke.
Now, let's examine the interface implementation:
var g2 greeter = t2 g2.hello() // Hello Smith g2.goodbye() // Goodbye Smith
Assigning a pointer variable t2 of type *tourGuide to a receiver value of interface type greeter succeeds because the pointer receiver allows for the acquisition of the value's address, which is then used as the receiver.
var g1 greeter = t1
However, assigning a non-pointer variable t1 of type tourGuide to a receiver value of interface type greeter fails. This is because a method with a pointer receiver requires a pointer receiver, and a value itself cannot be directly used as a pointer.
To summarize, methods with value receivers can be invoked using either a value or a pointer, while methods with pointer receivers can only be invoked using a pointer. When implementing interfaces with methods that have pointer receivers, it's crucial to use pointers as the underlying type.
The above is the detailed content of Value vs. Pointer Receivers in Go Interfaces: When Does Interface Assignment Fail?. For more information, please follow other related articles on the PHP Chinese website!