doushi3454 2019-04-07 21:44
浏览 228

golang和boltdb:使用闭包包装存储桶ForEach函数

In my code I use alot of repeating code to iterate over nested buckets in a bolddb database. I would like to do some refactoring, wrapping these repeating codes into new functions.

I know I need to use closures for this, but the extra db.View layer gives me headaches.

More precisely, I would like to wrap the bucket.ForEach function into a new function. This function creates a view transaction of the database, selects the nested bucket and returns a new function that lets me iterate over the given bucket.

The code signature of the newly created code would be something like this:

ForEachBucket(bucket_name string, *bolt.DB) func() {}

The code that I want to wrap:

func ForEachBucket(bucketname string, db *bolt.DB)  {

    db.View(func(tx *bolt.Tx) error {
        rootBkt := tx.Bucket([]byte("rootbucket")) // always the same
        interestingBkt := rootBkt.Bucket([]byte(bucketname))
        if nestedBkt := interestingBkt.Bucket([]byte("underlying")); nestedBkt != nil {
            mapBkt.ForEach(func(k, v []byte) error {
                // do something here
                    }
            })
            return nil
        })
}

I want to create a new function (using closures) that wraps the above code and returns a foreach like function.

  • 写回答

1条回答 默认 最新

  • douhuiqi3855 2019-04-10 14:32
    关注

    I didn't actually catch what you want, but I'll try to answer.

    You may have an callback argument that you pass to ForEach

        func ForEachBucket(db *bolt.DB, bucketname string, f func(b *bolt.Bucket) error {
            // ...
            return mapBucket.ForEach(f) // do not forget about returned error here
        }
    

    More general: https://play.golang.org/p/LQlZHOWZTfi

    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接