drde3456 2014-08-14 09:00
浏览 67

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?

  • 写回答

2条回答 默认 最新

  • dthy81285 2014-08-14 11:35
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度