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() }
几乎满足 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方法的指针接收器,并且只是避免满足错误接口(interface)的要求?
完整示例:
package main
import (
"fmt"
"os"
)
func main() {
e := os.PathError{Path: "/"}
printError(e)
}
func printError(e error) {
fmt.Println(e)
}
最佳答案
在此处阅读有关方法集的信息:https://golang.org/ref/spec#Method_sets
The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T)
您正在尝试使用 os.PathError
类型调用采用 error
接口(interface)的函数。根据上面的内容,它没有实现 Error() string
,因为该方法是在类型 *os.PathError
上定义的。
有了os.PathError
,您可以使用&
运算符获得*os.PathError
:
printError(&os.PathError{...})
关于go - os.PathError 未实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051486/