gpt4 book ai didi

go - os.PathError 没有实现错误

转载 作者:IT王子 更新时间:2023-10-29 01:53:58 25 4
gpt4 key购买 nike

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 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 方法使用指针接收器,而只是避免满足错误接口(interface)的要求?

完整示例:

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

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)

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

有了 os.PathError,您可以使用 & 运算符得到 *os.PathError:

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

关于go - os.PathError 没有实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com