Fec*_*ore 2 error-handling interface go
PathError在 Golang 的os库中找到的类型:
type PathError struct {
Op string
Path string
Err error
}
func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }
Run Code Online (Sandbox Code Playgroud)
几乎实现了 Go 的error界面:
type error interface {
Error() string
}
Run Code Online (Sandbox Code Playgroud)
但是,当尝试将其作为错误传递时,您会收到以下编译时错误:
cannot use (type os.PathError) as type error in argument...
os.PathError does not implement error (Error method has pointer receiver)
Run Code Online (Sandbox Code Playgroud)
为什么会os.PathError为 Error 方法使用指针接收器,而只是避免满足错误接口的要求?
完整示例:
package main
import (
"fmt"
"os"
)
func main() {
e := os.PathError{Path: "/"}
printError(e)
}
func printError(e error) {
fmt.Println(e)
}
Run Code Online (Sandbox Code Playgroud)
在此处阅读方法集:https : //golang.org/ref/spec#Method_sets
任何其他类型 T 的方法集由所有以接收者类型 T 声明的方法组成。 对应指针类型 *T 的方法集是所有以接收者 *T 或 T 声明的方法的集合(即,它还包含方法一组T)
您正在尝试error使用 type调用采用接口的函数os.PathError。根据上述,它没有实现Error() string,因为该方法是在 type 上定义的*os.PathError。
让os.PathError您可以*os.PathError使用&运算符:
printError(&os.PathError{...})