go - 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)
}
解决方案
在此处阅读有关方法集的信息: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{...})
推荐阅读
- java - 从 Java 8 中的地图列表中获取字符串
- ansible - 如何从 Ansible 中的所有主机获取变量?
- python-3.x - 为什么我的 GAN 在某个点之后没有产生更多好的图像?
- css - 是否可以动态调整列的数据单元格以使它们出现在同一垂直线上?
- android - 等待方法通道方法调用中的活动,然后将结果返回到颤振
- mysql - NodeJS Mysql查询在where子句中有多个字段
- node.js - 使用正则表达式字符集进行快速路由解析
- php - 在 Laravel 的模型中添加一个新字段
- python - 在python中增加文件名
- php - 将多个 Google Drive 文件下载为压缩文件