doupi8598 2018-05-11 23:22
浏览 33
已采纳

nil指针嵌入错误

Why do I get a nil pointer error when I try to print a pointer with an uninitialized embedded error:

package main

import (
  "log"
  "errors"
)

type Danger struct {
  error
}

func main() {
  // the nil pointer issue has to do with struct embedding an error value that is nil
  d := &Danger{}
  log.Println(d)

  d = &Danger{errors.New("foobar")}
  log.Println(d)
}

results in

2009/11/10 23:00:00 %!v(PANIC=runtime error: invalid memory address or nil pointer dereference)
2009/11/10 23:00:00 foobar

https://play.golang.org/p/fBuN0XonX9v

This came up in an interview today and neither interviewer nor interviewee could figure it out.

  • 写回答

1条回答 默认 最新

  • dongshan0202405 2018-05-12 00:00
    关注

    The spec says:

    Given a struct type S and a defined type T, promoted methods are included in the method set of the struct as follows:

    • If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.

    The fmt documentation says:

    If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

    From this, we can conclude that log.Println(d) will invoke the promoted Error method from the error field.

    If the error field is nil, then the call panics.

    The fmt documentation also says:

    If an Error or String method triggers a panic when called by a print routine, the fmt package reformats the error message from the panic, decorating it with an indication that it came through the fmt package.

    The text %!v(PANIC=runtime error: invalid memory address or nil pointer dereference) is the decorated panic value.

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?