如何在Golang回调函数中传递变量? [英] How to pass a variable in a Golang callback function?

查看:340
本文介绍了如何在Golang回调函数中传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  func loopThroughDirs(path string,fileInfo os.FileInfo,err error)error {
...做一些服务...
返回零
}

func main(){
service,err:= storage.New客户端)
...
filepath.Walk(* dirName,loopThroughDirs)
}

我想解决的问题是,我想在 loopThroughDirs()中使用 service 。如何做到这一点?



PS:
中的 loopThroughDirs 函数> filepath.Walk()在Go中调用回调?

解决方案

WalkFunc 函数:

  func main(){
service ,ERR:= storage.New(客户端)
...
filepath.Walk(*目录名,getWalkFunc(服务))
}

FUNC getWalkFunc(服务storage.Service)filepath.WalkFunc {
return func(path string,fileInfo os.FileInfo,err error)error {
// ...做一些服务...
return nil
}
}


I have the following code:

func loopThroughDirs(path string, fileInfo os.FileInfo, err error) error {
    ...do something with service...
    return nil
}

func main() {
    service, err := storage.New(client)
    ...
    filepath.Walk(*dirName, loopThroughDirs)
}

The problem I want to solve is this, I want to use service inside loopThroughDirs(). How do I do this?

PS: Is the loopThroughDirs function inside filepath.Walk() called a callback in Go?

解决方案

You can also try returning a WalkFuncfunction :

func main() {
    service, err := storage.New(client)
    ...
    filepath.Walk(*dirName, getWalkFunc(service))
}

func getWalkFunc(service storage.Service) filepath.WalkFunc {
    return func(path string, fileInfo os.FileInfo, err error) error {
        // ...do something with service...
        return nil
    }
}

这篇关于如何在Golang回调函数中传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆