Home >Backend Development >Golang >Why Can\'t Go Interfaces Directly Support Setter Methods, and How Can This Be Worked Around?

Why Can\'t Go Interfaces Directly Support Setter Methods, and How Can This Be Worked Around?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 00:50:14258browse

Why Can't Go Interfaces Directly Support Setter Methods, and How Can This Be Worked Around?

Polymorphism in Go: A Closer Look at Interface Methods and Pointer Receivers

In Go, polymorphism is not natively supported, but it can be achieved using interfaces. This introduces a common question: why aren't setter methods allowed for interfaces?

As demonstrated in the code provided, when the setter method is defined as a value receiver, changes made within the function are lost when it exits. Modifying the receiver to a pointer receiver allows for permanent changes, but it raises a compilation error.

To address this, Go provides a workaround. The corrected code modifies the receiver of the setter method to be a pointer. This enables the function to modify the underlying data structure and retain the changes. The modified code uses an interface, ensuring that the pointer receiver method is accessible through the interface.

package main

import "fmt"

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 this is not strictly polymorphism, it effectively achieves a similar result by using interfaces and pointer receivers. The code can be used to set properties through an interface, cleanly encapsulating data and operations.

The above is the detailed content of Why Can\'t Go Interfaces Directly Support Setter Methods, and How Can This Be Worked Around?. 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