Home > Backend Development > Golang > Does Go Support Polymorphism: Finding Workarounds for Setter Methods?

Does Go Support Polymorphism: Finding Workarounds for Setter Methods?

Patricia Arquette
Release: 2024-11-25 13:27:11
Original
246 people have browsed it

Does Go Support Polymorphism: Finding Workarounds for Setter Methods?

Polymorphism in Go: Does It Exist?

Polymorphism, the ability for objects of different classes to have identical methods, is a fundamental aspect of object-oriented programming. In Go, however, setter methods for interfaces appear to be unavailable.

Let's examine a basic example:

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

When this code is run, the Set method for the MyStruct type fails because the receiver is not a pointer. Any changes made to this are lost when the function exits.

One might attempt to fix this by changing the receiver to a pointer:

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

However, this would result in a compilation error. Interface methods in Go cannot have pointer receivers.

So, is there any way to achieve polymorphism in this scenario?

The closest alternative is to use an interface type and an anonymous struct that implements the interface:

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

var mi MyInterfacer = &MyStruct{123}
fmt.Println(mi.Get()) // prints 123

mi.Set(456)
fmt.Println(mi.Get()) // prints 456
Copy after login

While this solution is not true polymorphism, it utilizes an interface to provide a clean and flexible way to manipulate objects of different types.

The above is the detailed content of Does Go Support Polymorphism: Finding Workarounds for Setter Methods?. 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