ds9567 2019-09-23 11:30
浏览 49
已采纳

如何对变量使用多态[重复]

This question already has an answer here:

I am new in Go and started learning about polymorphism.
I know how to do it when multiple objects need to use the same function.
But I have a new problem, I don't know what to do in a case I have the same variable on different objects.

In the following example I have two different objects: struct1 and struct2. Both of them have the same variable name.
I can run over them and check which is which and work accordingly (you can test it here):

package main

import (
    "fmt"
)
type struct1 struct {
    name string
}

type struct2 struct {
    name string
}

func main(){
    structMap := make(map[string]interface{})
    s1 := struct1{name:"struct1_name"}
    s2 := struct2{name:"struct2_name"}
    structMap["struct1"] = s1
    structMap["struct2"] = s2

    for key, _ := range structMap {
        switch key {
            case "struct1":
                generic := structMap[key].(struct1)
                fmt.Println(generic.name)
            case "struct2":
                generic := structMap[key].(struct2)
                fmt.Println(generic.name)
        }
    }
}

But if I had 20 objects ? I would need to do 20 checks?
So I wonder if it possible to do an interface with variables, something like:

type genericStruct interfcae {
   name string
}

...
for key, _ := range structMap {
    generic := structMap[key].(genericStruct)
    fmt.Println(generic.name)

}

Of course this code doesn't work because I don't know how to do it, but I wanted to know about a way to do it.

EDIT:
I tried to use interface based on the example from: https://gobyexample.com/interfaces
Thanks for Robbie Milejczak and the other guys who help me.

This the new working code:

package main

import (
    "fmt"
)
type struct1 struct {
    name string
}

type struct2 struct {
    name string
}

type genericInterface interface {
    GetName() string
}

func (r struct1 ) GetName() string{
    return r.name
}

func (r struct2 ) GetName() string{
    return r.name
}

func printName(g interface{}){
    a := g.(genericInterface)
    fmt.Println(a.GetName())
}

func main(){
    structMap := make(map[string]interface{})
    s1 := struct1{name:"struct1_name"}
    s2 := struct2{name:"struct2_name"}
    structMap["struct1"] = s1
    structMap["struct2"] = s2

    for key, _ := range structMap {
    printName(structMap[key])
    }
}
</div>

展开全部

  • 写回答

1条回答 默认 最新

  • douchan0523 2019-09-23 11:51
    关注

    For this contrived example you could use getters / setters instead of static properties to leverage interfaces:

    type GenericStruct interface {
       GetName() string
    }
    

    And now any struct with a receiver called GetName will satisfy the GenericStruct interface:

    type MyStruct struct {
      Name string
    }
    
    func (ms *MyStruct) GetName() string {
      return ms.Name
    }
    

    This could get messy with more complex structs, in which case you may want to consider the composition suggestion (typically achieved via embedding) or a third party library such as genny

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥100 有能够实现人机模式的c/c++代码,有图片背景等,能够直接进行游戏
  • ¥20 校园网认证openwrt插件
  • ¥15 以AT89C51单片机芯片为核心来制作一个简易计算器,外部由4*4矩阵键盘和一个LCD1602字符型液晶显示屏构成,内部由一块AT89C51单片机构成,通过软件编程可实现简单加减乘除。
  • ¥15 某东JD算法逆向算法
  • ¥15 求GCMS辅导数据分析
  • ¥30 SD中的一段Unet下采样代码其中的resnet是谁跟谁进行残差连接
  • ¥15 Unet采样阶段的res_samples问题
  • ¥60 Python+pygame坦克大战游戏开发实验报告
  • ¥15 R语言regionNames()和demomap()无法选中中文地区的问题
  • ¥15 Open GL ES 的使用
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部