go - 零指针嵌入错误

标签 go null

当我尝试打印带有未初始化嵌入错误的指针时,为什么会出现 nil 指针错误:

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)
}

结果

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

这在今天的面试中出现,面试官和被面试者都搞不懂。

最佳答案

spec说:

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.

fmt文档说:

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).

由此,我们可以得出结论,log.Println(d) 将从 error 字段调用提升的 Error 方法。

如果 error 字段为 nil,则调用出现错误。

fmt 文档还说:

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.

文本 %!v(PANIC=runtime error: invalid memory address or nil pointer dereference) 是修饰的 panic 值。

关于go - 零指针嵌入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301438/

相关文章:

go - 如何将 *rsa.PublicKey 变成可识别的 key 字符串

c - malloc 返回 null 时动态数组清理

null - 使用 Redshift 将空值替换为最后一个非空值

go - Apache ignite SQL 插入失败

c++ - 在大型 C++ 代码库中避免空指针异常

c++ - 如何从返回类型为pair的C++函数返回等效的nullptr?

mysql - 如何根据没有数据的月份统计并选择所有记录

go - 如何获得带有反射的自定义类型?

go - ZMQ 无法接收来自多个发布者的消息

go - 生长 slice 和底层数组