为什么 go 编译器在满足接口时说结构不满足接口?

我可以看到scanner.go该结构有一个error方法。


// 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方法。


ABOUTYOU
浏览 132回答 1
1回答

肥皂起泡泡

事实证明这func (e *SyntaxError) Error() string { return e.msg }是指针的方法,而我正在寻找值的方法。我设法通过*json.SyntaxError引用指针来解决这个问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go