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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动