小编use*_*096的帖子

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

我想在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

5
推荐指数
2
解决办法
4402
查看次数

标签 统计

go ×1