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

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报