4

我正在尝试遍历 C 驱动器上的所有文件,这些文件在 Go中可能效率低下,但我不知道为什么我在执行此操作时不断收到恐慌错误,因为我告诉 walk 函数返回一个 nil 错误代码.

package files

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

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

func GetFiles() {
    err := filepath.Walk("C:\\", walkpath)
    if err != nil {
        fmt.Printf(err.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

您如何处理运行时发生的错误?

谢谢!

4

1 回答 1

6

您没有检查错误,而是尝试在 nilos.FileInfo接口上调用方法:

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

如果要panic在运行时处理 a ,可以使用recover. 然而,这应该是意外恐慌的最后手段。Apanic通常是由于编程错误,并旨在使程序崩溃。

于 2016-02-18T17:47:34.573 回答