登录
首页 >  Golang >  Go问答

Go语言中是否有类似C++中的绑定(bind)功能?

来源:stackoverflow

时间:2024-03-04 23:42:27 457浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《Go语言中是否有类似C++中的绑定(bind)功能?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

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

在 c++ 中:

class a {
public:
    typedef std::function 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类的成员函数read与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)
}

我也遇到过类似的问题。鉴于:

func method(f foo, b bar)

我想要:

var binded : func(b bar) = bind(method, foo{})

最终我只是使用了这个方法:

func (f Foo) BindableMethod(b Bar) {
    return Method(f, b)
}
var binded = Foo{}.BindedMethod

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>