Callback in Golang

Peter Hon picture Peter Hon · Aug 14, 2014 · Viewed 30.8k times · Source

I am using go-couchbase to update data to couchbase, however, I have problem in how to use the callback function.

The function Update requires me to pass a callback function in which should be UpdateFunc

func (b *Bucket) Update(k string, exp int, callback UpdateFunc) error

So that's what I have done

First, I declared a type UpdateFunc:

type UpdateFunc func(current []byte) (updated []byte, err error)

Then in the code, I add the following lines:

fn := UpdateFunc{func(0){}} 

and then call the Update function:

bucket.Update("12345", 0, fn()}

But the Go returns the following error:

syntax error: unexpected literal 0, expecting ) for this line fn := UpdateFunc{func(0){}}

So what I am doing wrong? So how can I make the callback function work ?

additional information

Thanks all of your suggestion. Now I can run the callback function as follows:

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

myb.Update("key123", 1, myfunc)

However, when I run the Update function of the bucket. I checked the couch database. The document with the key of "key123" was disappeared. It seems the Update does not update the value but delete it. What happened?

Answer

OneOfOne picture OneOfOne · Aug 14, 2014

You need to create a function that matches the couchbase.UpdateFunc signature then pass it to bucket.Update.

For example:

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

....

bucket.Update("12345",0,fn)

Notice that to pass a function you just pass fn not fn(), that would actually call the function right away and pass the return value of it.

I highly recommend stopping everything you're doing and reading Effective Go and all the posts on Go's blog starting with First Class Functions in Go.