dongshuobei1037 2016-04-19 14:04
浏览 15
已采纳

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

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条回答 默认 最新

  • douwo1517 2016-04-19 14:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据