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

Implementing interface from different package (callback from other module)

在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 中,我也想用接口和实现做同样的事情。

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

我可以覆盖文件 B.go 中接口函数的逻辑吗?我该怎么做才能让它们等同于NodeJS的风格?

我试试

import (A);
newA = A{}

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

Can I overwrite logic for interface functions in file 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
}

函数是 Go 中的第一个 class 值,就像它们在 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")
}