英文:
Why is the go compiler saying a struct does not satisfy an interface when it does?
问题
我可以看到在scanner.go
中,这个结构体有一个error
方法。
// A SyntaxError is a description of a JSON syntax error.
type SyntaxError struct {
msg string // 错误描述
Offset int64 // 错误发生在读取 Offset 字节之后
}
func (e *SyntaxError) Error() string { return e.msg }
但是编译器告诉我:
当我尝试在类型上进行switch case时,出现了api/errors.go:24: impossible type switch case: err (type error) cannot have dynamic type json.SyntaxError (missing Error method)
。
func myFunction(err error) {
switch err.(type) {
case validator.ErrorMap, json.SyntaxError:
response.WriteErrorString(http.StatusBadRequest, "400: Bad Request")
// etc
}
}
为什么这个代码不能编译通过?因为这个结构体有一个Error
方法。
英文:
I can see in scanner.go
that the struct has an error
method.
// A SyntaxError is a description of a JSON syntax error.
type SyntaxError struct {
msg string // description of error
Offset int64 // error occurred after reading Offset bytes
}
func (e *SyntaxError) Error() string { return e.msg }
But the compiler tells me this:
api/errors.go:24: impossible type switch case: err (type error) cannot have dynamic type json.SyntaxError (missing Error method)
when trying to do a switch case on type
func myFunction(err error) {
switch err.(type) {
case validator.ErrorMap, json.SyntaxError:
response.WriteErrorString(http.StatusBadRequest, "400: Bad Request")
//etc
Why does this not compile? Because the struct has the Error
method.
答案1
得分: 6
原文翻译如下:
原来 func (e *SyntaxError) Error() string { return e.msg }
是一个指针的方法,而我正在寻找一个值的方法。我通过使用 *json.SyntaxError
来引用一个指针,成功解决了这个问题。
英文:
It turns out that func (e *SyntaxError) Error() string { return e.msg }
is a method for the pointer, whereas I am looking for the method on a value. I've managed to solve the problem by doing *json.SyntaxError
to refer to a pointer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论