为什么Go编译器说一个结构体不满足接口,而实际上它是满足的?

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年4月19日 22:04:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/36720749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定