首页 > 解决方案 > os.PathError 没有实现错误

问题描述

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界面

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

标签: goerror-handlinginterface

解决方案


在此处阅读有关方法集的信息: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{...})


推荐阅读