gpt4 book ai didi

go - Go 中的多态性——它存在吗?

转载 作者:IT王子 更新时间:2023-10-29 01:22:27 25 4
gpt4 key购买 nike

我正在尝试在 Go 上做一些真正简单的事情:拥有一个带有 getter 和 setter 方法的接口(interface)。而且似乎不允许使用 setter 方法。

给定这段代码:

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())
}

Set 方法不起作用,因为在 func (this MyStruct) Set(i int) 中,this MyStruct 不是指针,并且一旦函数退出,更改就会丢失。但是将其设为 this *MyStruct 将无法编译。有什么解决方法吗?

最佳答案

这是您的代码 ( playground ) 的更正版本。这不完全是多态性,但接口(interface)的使用是很好的 Go 风格。

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())
}

关于go - Go 中的多态性——它存在吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com