duanjiu2701 2018-07-31 18:39
浏览 47
已采纳

Go中是否有类似于C ++绑定的内容?

I'm trying to do something in Go, similar to C++'s bind.
In 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);
    }
};

In another class 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 {};
};

when B's run() function is called, it will bind class B member function read with A's Handler. Then m_A.func(hander) is called, it will call getData(). The data got is then parsed to B::read(const string& data)

Is there any way to do it in Go? How to create a forwarding call wrapper in golang?

  • 写回答

1条回答 默认 最新

  • douguio0185 2018-08-06 20:20
    关注

    Solution:

    I'm posting my own solution for my question:

    I am passing go function as a parameter of another function to do the callback. The following code is a go version of the above C++ code.

    In 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
    }
    

    In B.go, A is a member of B struct

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?