duanhuang2150 2018-03-12 17:22
浏览 309

如何在golang的接口中添加新方法

I have a golang interface I

type I interface {
    A()
    B()
}

This interface is an element of type S struct. Now I want to add a function C() to this interface which will be called an object of type S. But this interface is implemented by many other types(for ex: T). And on compiling I get an error as T does not implement C().

One workaround for this is add a dummy implementation of C() in T which just returns a value of the T's return type.

Is there any better way to do this?

  • 写回答

1条回答 默认 最新

  • dqz7636 2018-03-12 18:20
    关注

    You can implement multiple interfaces with a single struct, as below. You would then have methods accept the different interfaces as arguments.

    If you need a single function which utilises methods from both interfaces you could just pass the pointer to your struct as separate arguments (one for each interface) but there is nothing stopping one interface satisfying multiple interfaces with a smaller scope so you could create a third interface which encapsulates the functionality of both to handle these situations (See IJ interface example).

    package main
    
    import (
        "fmt"
    )
    
    type I interface {
        A()
        B()
    }
    
    // interface 'J' could be defined in an external package, it doesn't matter
    type J interface {
        C()
    }
    
    // encapsulate I & J interfaces as IJ
    type IJ interface {
        J
        I
    }
    
    // S will satisfy interfaces I, J & IJ
    type S struct {}
    
    func (s *S) A(){
        fmt.Println("A")
    }
    
    func (s *S) B(){
        fmt.Println("B")
    }
    
    func (s *S) C(){
        fmt.Println("C")
    }
    
    
    func main() {
        s := &S{}
        doWithI(s)
        doWithJ(s)
        fmt.Println("===================================")
        doWithIAndJ(s)
    }
    
    func doWithI(in I){
        in.A()
        in.B()
    }
    
    func doWithJ(in J){
        in.C()
    }
    
    func doWithIAndJ(in IJ){
        in.A()
        in.B()
        in.C()
    }
    

    https://play.golang.org/p/DwH7Sr3zf_Y

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值