duanbaque4230 2018-07-18 20:05
浏览 547
已采纳

如何在GoLang中将项目追加到[] os.FileInfo

I'm making a function like ioutil.ReadDir() but recursively due I want all the files in folders and subfolders and ioutil.ReadDir() just do it in the specified folder but I don't know how to append items to an array of []os.FileInfo that I've created.

This is what I have:

func GetFilesRecursively(searchDirectory string) (foundFileList []os.FileInfo, errorGenerated error){

   fileList := []os.FileInfo{}
   allFilesAndFolders := []string{}

   //Get all the files and directories
   err := filepath.Walk(searchDirectory, func(path string, f os.FileInfo, err error) error {
       allFilesAndFolders = append(allFilesAndFolders, path)
       return nil
   })

   // Remove directories due those are also added into the array and we don't need them
   for _, file := range allFilesAndFolders{

       fileInfo, _ := os.Stat(file)

       if (!fileInfo.Mode().IsDir()){
          fileList = append(fileList, file) //error here!!
       }
   }

   return fileList, err
}

The error is in the comments in the code snippet above

How could I do that?

  • 写回答

1条回答 默认 最新

  • dongrou5254 2018-07-22 07:30
    关注

    You try to append a string to an array of os.FileInfo. That is a type error.

    Here is a version of your code that does what you want and looks more Go-like, with shorter variable names, unnamed return types (their types perfectly decribe what they do) and using var to create an empty slice.

    func GetFilesRecursively(root string) ([]os.FileInfo, error) {
        var files []os.FileInfo
    
        // walk all directories but only collect files
        err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
            if !f.IsDir() {
                files = append(files, f)
            }
            return nil
        })
    
        return files, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?