drryyiuib43562604 2019-05-04 22:24
浏览 15
已采纳

Go可以避免使用中间接口吗?

I am trying to see if Go supports a language feature I use in other OO languages (such as Java). I'd like to define a few interfaces and pass an object that supports some of them to a function as a parameter.

In Java I might define a bunch of single method interfaces like HasAdd, HadMul, HasSub, HasDiv, HasSin, HasCos, HasTan, etc.

And then I might define a generic method whose argument T is defined as <T extends HasSin & HasAdd>. I pass in a T to the method. Note I don't have to define an intermediate Interface that contains both HasSin and HasAdd. (Which is great because n interfaces results in needing 2^n intermediate interfaces to cover all cases).

I know go does not support generics. But can it do something like func(HasSin & HasAdd obj)? It seems it should support this behavior. I just haven't found documentation that cinches it either way.

I have seen this: https://golangbot.com/interfaces-part-2/ where there is an example of something similar near the bottom of the article but it does indeed use an intermediate interface.

  • 写回答

1条回答 默认 最新

  • douqian1975 2019-05-04 22:34
    关注

    Declare an interface with the methods required by the function:

    type SinAdder interface {
        Sin(float64) float64
        Add(float64, float64) float64
    }
    

    If you declared the single method interfaces Siner and Adder, then you can declare SinAdder in terms of those interfaces:

    type SinAdder interface {
        Siner
        Adder
    }
    

    Use that interface in the function:

    func example(arg SinAdder) {
    }
    

    Any value that has the Sin and Add methods can be passed to example.

    You can void declaring the SinAdder interface by using an anonymous interface definition in the function argument:

    func example(arg interface { Siner; Adder }) {
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路