2016-04-19 26 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來引用指針來解決問題。