2016-04-19 27 views
2

我可以在scanner.go看到该结构有一个error方法。为什么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: 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方法。

回答

6

事实证明func (e *SyntaxError) Error() string { return e.msg }是一个指针的方法,而我正在寻找一个值的方法。我设法通过*json.SyntaxError来引用指针来解决问题。