【问题标题】:os.PathError does not implement erroros.PathError 没有实现错误
【发布时间】: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


【解决方案1】:

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

任何其他类型 T 的方法集由所有声明为接收者类型 T 的方法组成。对应指针类型 *T 的方法集是所有声明为接收者 *T 或 T 的方法集(即它也包含T的方法集)

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多