首页 > 解决方案 > Go中有没有类似于C++绑定的东西?

问题描述

我正在尝试在 Go 中做一些事情,类似于 C++ 的绑定。
在 C++ 中:

class A {
public:
    typedef std::function<bool(const string&)> Handler;
    bool func(A::Handler& handler) {
        // getData will get data from file at path
        auto data = getData(path);
        return handler(data);
    }
};

在另一个 B 类中:

Class B {
public:
    bool run() {
        using namespace std::placeholders;
        A::Handler handler = bind(&B::read, this, _1);
        m_A.initialize();
        return m_A.func(handler);
    }
    bool read(const string& data) {
        std::out << data << std::endl;
    }
private:
    A m_A {};
};

当 B 的 run() 函数被调用时,它将 B 类的成员函数读取与 A 的 Handler 绑定。然后m_A.func(hander)被调用,它会调用getData()。然后将得到的数据解析为B::read(const string& data)

有没有办法在 Go 中做到这一点?如何在 golang 中创建转发呼叫包装器?

标签: gocallback

解决方案


解决方案:

我正在为我的问题发布我自己的解决方案:

我将 go 函数作为另一个函数的参数传递来执行回调。以下代码是上述 C++ 代码的 go 版本。

A.go

type A struct {
    //... some properties
}

type Handler func(string) bool
func (a *A) ReadRecords(handler Handler) bool {
    // getData will get data from file at path
    auto data = getData(path)
    return handler(data)
}

func (a *A) Initialize() {
    //... Initialization
}

B.go中,A 是 B 结构的成员

type B struct {
    a    A
    //...other properties
}

var read A.Handler
func (b *B) Run() bool {
    read = func(data string) {
        fmt.Println(data)
    }
    b.a.Initialize()
    return b.a.ReadRecords(read)
}

推荐阅读