当我尝试打印带有未初始化嵌入错误的指针时,为什么会出现 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/