【问题标题】:Implementing interface from different package (callback from other module)从不同的包实现接口(来自其他模块的回调)
【发布时间】:2019-04-29 01:42:43
【问题描述】:

在NodeJS中,我可以在一处声明回调,在一处使用,避免破坏项目结构。

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!"));

在 Go 中,我也想对接口和实现做同样的事情。

去吧

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

去吧

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

我可以覆盖 B.go 文件中接口函数的逻辑吗?我怎样才能使它们与 NodeJS 的样式等效?

我试试

import (A);
newA = A{}

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

【问题讨论】:

  • 您的 Go 代码无效,甚至无法编译。但与您的问题更直接相关:请解释您的最终目标。你到底想完成什么?您可能无法像在 Node 中那样做,但您可能会以某种方式做到这一点。专注于您要解决的问题,而不是您想象的解决方案。
  • 感谢您的评论。我想覆盖 AStruct 在文件 b.go 中实现的 canDoSomething 的 func DoSomething。我知道我的代码无法编译和运行,但我想每个人都能理解我想要做什么
  • 回调与想要覆盖一个方法有什么关系?
  • “覆盖”这个词对我来说就像是一个翻译工件。 NodeJS 代码中也没有覆盖。看起来预期的意思是“分配”。

标签: node.js go interface callback implements


【解决方案1】:

函数是 Go 中的一等值,就像它们在 JavaScript 中一样。您在这里不需要界面(除非您没有说明其他目标):

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")
}

由于所有类型都可以有方法,所以所有类型(包括函数类型)都可以实现接口。因此,如果您真的愿意,可以让 A 依赖于一个接口并定义一个函数类型以即时提供实现:

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")
}

【讨论】:

  • 非常感谢
【解决方案2】:

我可以覆盖 B.go 文件中接口函数的逻辑吗?

不,Go(和其他语言)中的接口没有任何逻辑或实现。

要在 Go 中实现一个接口,我们只需要实现接口中的所有方法。

A 和 B 类型如何以不同的逻辑实现相同的接口:

type Doer interface {
    Do(string)
}

type A struct {
    name string
}
func (a *A) Do(name string){
    a.name = name;
    // do one thing
}

type B struct {
    name string
}
func (b *B) Do(name string){
    b.name = name;
    // do another thing
}

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 2015-04-24
    • 2019-01-09
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多