dsa122870 2017-07-12 11:06
浏览 68
已采纳

具有多种返回类型的接口方法

I come from java and currently try to learn go. I'm struggeling with interface

consider this :

type Generatorer interface {
    getValue() // which type should I put here ? 
}

type StringGenerator struct {
    length         int
}

type IntGenerator struct {
    min            int
    max            int
}

func (g StringGenerator) getValue() string {
    return "randomString"
}

func (g IntGenerator) getValue() int {
    return 1
}

I want the getValue() function to return a string or an int, depending on if it's called from StringGenerator or IntGenerator

When I try to compile this, I get folowing error :

cannot use s (type *StringGenerator) as type Generatorer in array or slice literal: *StringGenerator does not implement Generatorer (wrong type for getValue method)

have getValue() string
want getValue()

How can I achieve this ?

  • 写回答

2条回答 默认 最新

  • dongxiong4571 2017-07-12 12:12
    关注

    You could achieve it in this way:

    type Generatorer interface {
        getValue() interface{}
    }
    
    type StringGenerator struct {
        length         int
    }
    
    type IntGenerator struct {
        min            int
        max            int
    }
    
    func (g StringGenerator) getValue() interface{} {
        return "randomString"
    }
    
    func (g IntGenerator) getValue() interface{} {
        return 1
    }
    

    The empty interface allows every value. This allows for generic code but basically stops you from using the very powerful type system of Go.

    In your example if you use the getValue function, you will get a variable of type interface{} and if you want to work with it, you need to know if it actually is a string or an int: you will need a lot of reflect making your code slow.

    Coming from Python I was used to code very generic. When learning Go I had to stop thinking that way.

    What that means in your specific case I can't say because I don't know what StringGenerator and IntGenerator are being used for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用