Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback in Golang

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?

like image 577
Peter Hon Avatar asked Aug 14 '14 09:08

Peter Hon


2 Answers

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.

like image 71
OneOfOne Avatar answered Oct 07 '22 01:10

OneOfOne


Same answer I posted on the go-nuts list, just in case:

You don't have to define the UpdateFunc type by yourself, it's already defined here:

https://github.com/couchbaselabs/go-couchbase/blob/master/client.go#L608

just define the function normally and pass it as an argument or pass an anonymous function as in other languages.

here's a simple example:

http://play.golang.org/p/YOKxRtQqmU

like image 37
DallaRosa Avatar answered Oct 07 '22 01:10

DallaRosa