go - os.PathError 未实现错误

标签 go error-handling interface

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/

相关文章:

javascript - typescript 将 `interface` 键作为字符串的并集传播

sql - 如何在golang中安装包

string - 将字符串转换为二进制字符串表示的有效方法

python - Openslide libjpeg 错误 : Wrong JPEG library version

python - 警报弹出窗口异常处理Python Selenium

java - 与内部实现的接口(interface)——好还是坏

go - 是否可以在结构之间进行转换?

go - 选择和上下文。上下文完成 channel

c - 我的实现未能删除 c 中 String 的最后一个字符

java - java接口(interface)如何调用对象类的方法