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

use*_*096 5 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不会编译.有没有解决方法?

Nic*_*ood 7

这是您的代码(游乐场)的更正版本.这不完全是多态性,但使用界面是很好的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())
}
Run Code Online (Sandbox Code Playgroud)


Cle*_*ric 2

回答帖子标题中的问题:

Go 不使用类,但提供了许多相同的功能:

* message passing with methods
* automatic message delegation via embedding
* polymorphism via interfaces
* namespacing via exports
Run Code Online (Sandbox Code Playgroud)

来自: http: //nathany.com/good/

解决你提供的代码,我将留给一些更有学识的 Gopher