douchen9569
2018-06-26 21:17
浏览 39
已采纳

os.PathError没有实现错误

The PathError type found in Golang's os library:

type PathError struct {
    Op   string
    Path string
    Err  error
}

func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }

nearly fulfills Go's error interface:

type error interface {
    Error() string
}

However, when trying to pass it as an error, you get the following compile time error:

cannot use (type os.PathError) as type error in argument... 
os.PathError does not implement error (Error method has pointer receiver)

Why would os.PathError use a pointer receiver for the Error method, and just avoid meeting the requirements of the error interface?

Full example:

package main

import (
    "fmt"
    "os"
)

func main() {
    e := os.PathError{Path: "/"}
    printError(e)
}

func printError(e error) {
    fmt.Println(e)
}

图片转代码服务由CSDN问答提供 功能建议

在Golang的 os 库中找到的 PathError 类型:

   type PathError struct {
操作字符串
路径字符串
 Err错误
} 
 
func(e * PathError)Error()字符串{return e.Op +“” + e.Path +“:  “ + e.Err.Error()} 
   
 
 

几乎实现了Go的 错误接口

 类型错误接口{
 Error()字符串
} 
   
 
 

但是,当尝试将其作为错误传递时,会出现以下编译时错误:

 不能使用(os.PathError类型)作为参数中的类型错误... 
os.PathError没有实现错误(Error方法具有指针接收器)
   
 
 

为什么 os.PathError 为Err使用指针接收器 或方法,而只是避免满足错误界面的要求?

完整示例:

  package main 
 
import(\  n“ fmt” 
“ os” 
)
 
func main(){
e:= os.PathError {路径:“ /”} 
 printError(e)
} 
 
func printError(e 错误){
 fmt.Println(e)
} 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushi4956 2018-06-26 22:48
    已采纳

    Read about method sets here: 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)

    You are trying to call a function taking the error interface using type os.PathError. According to the above, it does not implement Error() string, because that method is defined on type *os.PathError.

    Having os.PathError you can get *os.PathError using the & operator:

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题