dstbp22002 2018-11-27 10:28
浏览 158
已采纳

从不同的包实现接口(从其他模块回调)

In NodeJS, I can declare a callback in one place and use it in one place to avoid breaking the structure of the project.

A.js

module.exports = class A(){
    constructor(name, callback){
        this.name = name;
        this.callback = callback;
    }
    doSomeThingWithName(name){
        this.name = name;
        if(this.callback){
            this.callback();
        }
    }
}

B.js

const A = require(./A);
newA = new A("KimKim", ()=> console.log("Say Oyeah!"));

In Go, I also want to do the same thing like this with interface and implement.

A.go

type canDoSomething interface {
    DoSomething()
}
type AStruct struct {
    name string
    callback canDoSomething
}
func (a *AStruct) DoSomeThingWithName(name string){
    a.name = name;
    a.callback.DoSomething()
}

B.go

import (A);
newA = A{}
newA.DoSomeThingWithName("KimKim");

Can I overwrite logic for interface functions in file B.go? How could I do to make them equivalent to NodeJS's style?

I try

import (A);
newA = A{}

// I want
//newA.callback.DoSomething = func(){}...
// or
// func (a *AStruct) DoSomething(){}...
// :/
newA.DoSomeThingWithName("KimKim");
  • 写回答

2条回答 默认 最新

  • doujuncuo9339 2018-11-27 11:32
    关注

    Functions are first class values in Go, just like they are in JavaScript. You don't need an interface here (unless there is some other goal that you are not stating):

    type A struct {
        name string
        callback func()
    }
    
    func (a *A) DoSomeThingWithName(name string){
        a.name = name;
        a.callback()
    }
    
    func main() {
        a := &A{
            callback: func() { /* ... */ },
        }
    
        a.DoSomeThingWithName("KimKim")
    }
    

    Since all types can have methods, all types (including function types) can implement interfaces. So if you really want to you can let A depend on an interface and define a function type for providing implementations on-the-fly:

    type Doer interface {
        Do()
    }
    
    // DoerFunc is a function type that turns any func() into a Doer.
    type DoerFunc func()
    
    // Do implements Doer
    func (f DoerFunc) Do() { f() }
    
    type A struct {
        name     string
        callback Doer
    }
    
    func (a *A) DoSomeThingWithName(name string) {
        a.name = name
        a.callback.Do()
    }
    
    func main() {
        a := &A{
            callback: DoerFunc(func() { /* ... */ }),
        }
    
        a.DoSomeThingWithName("KimKim")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?