Home  >  Article  >  Backend Development  >  Why Do Go\'s Interface Setter Methods Require Pointers?

Why Do Go\'s Interface Setter Methods Require Pointers?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 11:35:26117browse

Why Do Go's Interface Setter Methods Require Pointers?

Polymorphism in Go: Interface Implementation

While Go does not support traditional polymorphism, interfaces provide a means to achieve a similar effect. However, limitations exist when implementing setter methods.

The Problem

Consider the following code:

type MyInterfacer interface {
    Get() int
    Set(i int)
}

type MyStruct struct {
    data int
}

func (this MyStruct) Get() int {
    return this.data
}

Attempting to implement the Set method results in an error:

func (this MyStruct) Set(i int) {
    this.data = i
}

Solution

To circumvent this limitation, the receiver in the Set method must be a pointer, as in:

func (this *MyStruct) Set(i int) {
    this.data = i
}

This allows the method to modify the underlying data, which is reflected in the interface variable.

Corrected Code

The following corrected code works as intended:

type MyInterfacer interface {
    Get() int
    Set(i int)
}

type MyStruct struct {
    data int
}

func (this *MyStruct) Get() int {
    return this.data
}

func (this *MyStruct) Set(i int) {
    this.data = i
}

func main() {
    s := &MyStruct{123}
    fmt.Println(s.Get())

    s.Set(456)
    fmt.Println(s.Get())

    var mi MyInterfacer = s
    mi.Set(789)
    fmt.Println(mi.Get())
}

While not true polymorphism, this technique allows for a similar level of flexibility through interface implementation in Go.

The above is the detailed content of Why Do Go\'s Interface Setter Methods Require Pointers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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