Home > Backend Development > Golang > How Can Polymorphism Be Achieved with Setters in Go?

How Can Polymorphism Be Achieved with Setters in Go?

Linda Hamilton
Release: 2024-12-10 10:41:10
Original
879 people have browsed it

How Can Polymorphism Be Achieved with Setters in Go?

Polymorphism in Go: Decoding the Setter Conundrum

In the realm of object-oriented programming, polymorphism enables objects of different classes to be treated as instances of a common super-type. However, in Go, the question arises: does polymorphism exist and, if so, how does it manifest?

Consider the following Go code, where an attempt is made to create an interface with getter and setter methods:

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

However, the setter method encounters an issue: the receiver this MyStruct is not a pointer, resulting in any changes made within the method being lost once it exits. Moreover, making the receiver this *MyStruct would hinder compilation.

To address this, a corrected version of the code utilizes pointers:

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

By introducing pointers, we enable changes made within the setter method to persist beyond its scope. While this technique may not constitute strict polymorphism in the traditional sense, it adheres to sound Go practices and provides a viable solution to the initial issue.

The above is the detailed content of How Can Polymorphism Be Achieved with Setters in Go?. 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