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

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

Barbara Streisand
Release: 2024-11-23 11:35:26
Original
178 people have browsed it

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
}
Copy after login

Attempting to implement the Set method results in an error:

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

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
}
Copy after login

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())
}
Copy after login

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!

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