go - 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 中创建转发呼叫包装器?
解决方案
解决方案:
我正在为我的问题发布我自己的解决方案:
我将 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)
}
推荐阅读
- javascript - 如何使用 React 中的“get”方法提交表单?
- vim - VSCodeVim - 如何正确绑定文本插入?
- database - 在 MongoDB 聚合中组合多个投影
- python - 需要在文本文件中搜索一个值,然后从文本文件 python3x 中提取值所在的行
- javascript - 如何检查鼠标是否离开页面?
- discord.js - 此错误“DiscordAPIError:缺少权限”不会停止
- ms-word - 如何在长字符串上循环搜索?
- c++ - 如何取消设置 std::cout 精度?
- java - 尝试从 Raspberry Pi 流式传输视频时,Android 应用程序崩溃
- javascript - 组件正在更改要控制的文本类型的不受控输入?