Why Can\'t a Go Struct with a Pointer Receiver Method Satisfy an Interface?

Mary-Kate Olsen
Release: 2024-11-19 17:56:02
Original
863 people have browsed it

Why Can't a Go Struct with a Pointer Receiver Method Satisfy an Interface?

Types of Go Struct Methods Satisfying an Interface

In Go, structs can have methods with varying receiver types (value or pointer). While a method with a value receiver can be called on either a value or a pointer of the struct, a method with a pointer receiver requires a pointer receiver.

Consider the example provided:

type greeter interface {
    hello()
    goodbye()
}

type tourGuide struct {
    name string
}

func (t tourGuide) hello()    { fmt.Println("Hello", t.name) }
func (t *tourGuide) goodbye() { fmt.Println("Goodbye", t.name) }
Copy after login

We can call the methods of tourGuide using both a value t1 and a pointer t2. However, when implementing interfaces, assigning a tourGuide value to a greeter interface variable is not allowed.

The reason for this is that if a method has a pointer receiver, only a pointer value can be used as the receiver. Since interface values are copies of the wrapped values and not addressable, they cannot be passed to methods with pointer receivers.

This restriction prevents potential issues where modifications made through the pointer receiver would only affect the copy in the interface, not the original value.

Hence, for an interface to accept a value type, all of its methods must have value receivers. In our example, since goodbye has a pointer receiver, tourGuide cannot be assigned to greeter.

The above is the detailed content of Why Can\'t a Go Struct with a Pointer Receiver Method Satisfy an Interface?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template