douxiong3245 2016-01-07 19:54
浏览 99

如何在Go中将Map传递给回调函数

I am trying to write a Go program to walk down a directory and find certain file and store that information in a Map. Here is what I have so far. I am not sure how to pass the Map to the visit function since it's a callback function.

..
type MyFile struct {
    Name       string
    FilePath    string
    FileMD5Hash [16]byte
}

func visit(path string, f os.FileInfo, err error) error {

    fileName := f.Name()
    if !f.IsDir() && strings.Contains(strings.ToLower(fileName), "myfile") {
        df := parseFile(path)
        fmt.Printf("Visited: %s [%x], %s, %s
", df.FilePath)
    }

    return nil
}

func parseFile(path string)...

func check(e error) ...

func WalkDir(path string) {
    err := filepath.Walk(path, visit)
    fmt.Printf("filepath.Walk() returned %v
", err)
}
  • 写回答

2条回答 默认 最新

  • drh78568 2016-01-07 20:09
    关注

    Pass the Map to the function which returns a filepath.WalkFunc and then pass it to filepath.Walk. It is a constructor like thing.

    func visit(map Map) filepath.WalkFunc {
        return func(path string, f os.FileInfo, err error) error {
    
            // do something with map
    
            fileName := f.Name()
            if !f.IsDir() && strings.Contains(strings.ToLower(fileName), "myfile") {
                df := parseFile(path)
                fmt.Printf("Visited: %s [%x], %s, %s
    ", df.FilePath)
            }
    
            return nil
        }
    }
    
    func WalkDir(path string) {
        err := filepath.Walk(path, visit(map))
        fmt.Printf("filepath.Walk() returned %v
    ", err)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答