为什么go编译器说结构不满足接口,而它满足接口?
我可以在为什么go编译器说结构不满足接口,而它满足接口?,go,Go,我可以在scanner.go中看到结构有一个错误方法 // 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() s
scanner.go
中看到结构有一个错误
方法
// 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 }
但编译器告诉我:
api/errors.go:24:不可能的类型切换案例:err(类型错误)在尝试对类型执行切换案例时不能具有动态类型json.SyntaxError(缺少错误方法)
func myFunction(err error) {
switch err.(type) {
case validator.ErrorMap, json.SyntaxError:
response.WriteErrorString(http.StatusBadRequest, "400: Bad Request")
//etc
为什么不编译?因为结构有
Error
方法。结果是func(e*SyntaxError)Error()字符串{return e.msg}
是指针的方法,而我是在值上查找方法。我通过执行*json.SyntaxError
来引用指针,成功地解决了这个问题
// 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 }