doupin8555 2016-02-18 17:28
浏览 224
已采纳

Golang Filepath.Walk在大型目录上出现恐慌错误

I am trying to walk through all files on the C drive which I read can be inefficient in Go, but I can't work out why I keep getting a panic error when doing this as I tell the walk function to return a nil error code.

package files

import (
   "path/filepath"
   "os"
   "fmt"
 )

func walkpath(path string, f os.FileInfo, err error) error {
    fmt.Printf("%s with %d bytes
", path,f.Size())
    return nil
}

func GetFiles() {
    err := filepath.Walk("C:\\", walkpath)
    if err != nil {
        fmt.Printf(err.Error())
    }
}

Panic error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x40 pc=0x46d0d6]

goroutine 1 [running]:
files.walkpath(0xc0820a8f80, 0xf, 0x0, 0x0, 0x664270, 0xc082408840, 0x0, 0x0)
        C:/project/src/files/files.go:11 +0x66
path/filepath.walk(0x529140, 0x3, 0x6641e8, 0xc082012240, 0x560d50, 0x0, 0x0)
        c:/go/src/path/filepath/path.go:370 +0x41c
path/filepath.Walk(0x529140, 0x3, 0x560d50, 0x0, 0x0)
        c:/go/src/path/filepath/path.go:396 +0xe8
files.GetFiles()
        C:/project/src/files/files.go:22 +0xc9
main.main()
        c:/project/src/main.go:12 +0x49
exit status 2

c:\project>go build c:\project\src\main.go

https://gobyexample.com/panic

How do you handle errors which occur during runtime?

Thanks!

  • 写回答

1条回答 默认 最新

  • dougu3591 2016-02-18 17:47
    关注

    You're not checking the error, and trying to call a method on a nil os.FileInfo interface:

    func walkpath(path string, f os.FileInfo, err error) error {
        if err != nil {
            fmt.Println(err)
        } else {    
            fmt.Printf("%s with %d bytes
    ", path,f.Size())
        }
        return nil
    }
    

    If you want to handle a panic at runtime, you can use recover. This should however be a last resort for unexpected panics. A panic is usually because of a programming error, and is intended to crash the program.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?