Golang中的回调

Pet*_*Hon 3 callback go couchbase

我正在使用go-couchbase将数据更新到couchbase,但是,我在如何使用回调函数方面遇到了问题.

该函数Update要求我传递一个回调函数UpdateFunc

func (b *Bucket) Update(k string, exp int, callback UpdateFunc) error
Run Code Online (Sandbox Code Playgroud)

这就是我所做的

首先,我声明了一种类型UpdateFunc:

type UpdateFunc func(current []byte) (updated []byte, err error)
Run Code Online (Sandbox Code Playgroud)

然后在代码中,我添加以下行:

fn := UpdateFunc{func(0){}} 
Run Code Online (Sandbox Code Playgroud)

然后调用Update函数:

bucket.Update("12345", 0, fn()}
Run Code Online (Sandbox Code Playgroud)

但Go返回以下错误:

syntax error: unexpected literal 0, expecting ) for this line fn := UpdateFunc{func(0){}}
Run Code Online (Sandbox Code Playgroud)

那么我做错了什么?那么如何使回调函数工作呢?

附加信息

谢谢你的所有建议.现在我可以运行回调函数,如下所示:

myfunc := func(current []byte)(updated []byte, err error) {return updated, err }

myb.Update("key123", 1, myfunc)
Run Code Online (Sandbox Code Playgroud)

但是,当我运行桶的更新功能时.我检查了沙发数据库.带有"key123"键的文件消失了.似乎更新不更新值但删除它.发生了什么?

One*_*One 5

您需要创建一个与couchbase.UpdateFunc签名匹配的函数,然后将其传递给bucket.Update.

例如:

fn := func(current []byte) (updated []byte, err error) {
    updated = make([]byte, len(current))
    copy(updated, current)
    //modify updated
    return
}

....

bucket.Update("12345",0,fn)
Run Code Online (Sandbox Code Playgroud)

请注意,传递一个函数,你只是传递fnfn(),这实际上会调用该函数马上并通过它的返回值.

我强烈建议你停止你正在做的所有事情并阅读Effective Go和Go的博客上的所有帖子,从Go中的First Class Functions开始.