os.PathError没有实现错误

时间:2018-06-26 21:17:33

标签: go error-handling interface

在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)
}

1 个答案:

答案 0 :(得分:4)

在此处了解方法集:https://golang.org/ref/spec#Method_sets

  

任何其他类型T的方法集都包含以接收者类型T声明的所有方法。相应的指针类型* T的方法集是所有以接收者* T或T声明的方法的集合(也就是说,包含方法集T)

您正在尝试使用类型error调用带有os.PathError接口的函数。根据以上所述,它没有实现Error() string,因为该方法是在类型*os.PathError上定义的。

有了os.PathError,您可以使用*os.PathError运算符获取&

printError(&os.PathError{...})

相关问题