doufan6544 2014-04-22 06:07
浏览 15

Go中的多态性-是否存在?

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?

  • 写回答

4条回答 默认 最新

  • doudong8713 2014-04-22 06:18
    关注

    To answer the question the in the title to post:

    Go does not use classes, but provides many of the same features:

    * message passing with methods
    * automatic message delegation via embedding
    * polymorphism via interfaces
    * namespacing via exports
    

    From: http://nathany.com/good/

    Solving the code you supplied, I will leave to some more learned Gopher

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line