【发布时间】:2018-06-26 21:17:33
【问题描述】:
在 Golang 的 os 库中找到的 PathError 类型:
type PathError struct {
Op string
Path string
Err error
}
func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }
几乎满足 Go 的 error interface:
type error interface {
Error() string
}
但是,当尝试将其作为错误传递时,您会收到以下编译时错误:
cannot use (type os.PathError) as type error in argument...
os.PathError does not implement error (Error method has pointer receiver)
为什么os.PathError会为Error方法使用指针接收器,而只是避免满足错误接口的要求?
完整示例:
package main
import (
"fmt"
"os"
)
func main() {
e := os.PathError{Path: "/"}
printError(e)
}
func printError(e error) {
fmt.Println(e)
}
【问题讨论】:
-
编译错误说:“错误方法有指针接收器”。您需要使用指针。
-
printError(&e)会更好。 -
(当你跳回 Go 并严重需要复习时。)在旁注中,我在搜索
os.PathError时偶然发现了 Dave Cheney 的出色 article on errors。
标签: go error-handling interface