Go中的多态性 - 它存在吗? [英] Polymorphism in Go - does it exist?
本文介绍了Go中的多态性 - 它存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在Go上做一些简单的事情:为getter和setter方法提供一个接口。看来setter方法是不允许的。
给出以下代码:
包主
导入fmt
类型MyInterfacer接口{
Get()int
Set(i int)
}
类型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())
}
$ b $ Set 方法不起作用,因为在 func(this MyStruct)Set(i int )
,这个MyStruct
不是一个指针,并且这个改变在函数退出后立即丢失。但是使它这个* MyStruct
不会被编译。是否有任何解决方法?解决方案这是您的代码的修正版本(playground )。这不完全是Polymorphism,但使用一个接口是很好的Go风格。
包主
importfmt
类型MyInterfacer接口{
Get()int
Set(i int)
}
类型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())
}
I am trying to make something real simple on Go: to have an interface with getter and setter methods. And it seems setter methods are not allowed.
Given this code:
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
method does not work, because in func (this MyStruct) Set(i int)
, this MyStruct
is not a pointer, and the changes are lost as soon at the function exits. But making it this *MyStruct
would not compile. Is there any workaround?
解决方案 Here is a corrected version of your code (playground). This isn't exactly Polymorphism, but the use of an interface is good Go style.
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中的多态性 - 它存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文