我想在Go上做一些非常简单的东西:有一个getter和setter方法的接口.并且似乎不允许使用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())
}
Run Code Online (Sandbox Code Playgroud)
Set方法不起作用,因为in func (this MyStruct) Set(i int), this MyStruct不是指针,并且在函数退出时很快就会丢失更改.但是它this *MyStruct不会编译.有没有解决方法?
go ×1