[英]Panic when printing a nil error in a struct
The following code will panic when printing a nil value of an error type field in a struct. 当在结构中打印错误类型字段的nil值时,以下代码会惊慌。 Why?
为什么?
package main
import (
"fmt"
)
type ta struct {
int
}
type tb struct {
int
*ta
}
type tc struct {
int
error
}
type td struct {
int
error interface{}
}
func main() {
fmt.Println(fmt.Sprintf("%v", ta{1}))
fmt.Println(fmt.Sprintf("%v", tb{1, nil}))
fmt.Println(fmt.Sprintf("%v", tc{1, nil}))
fmt.Println(fmt.Sprintf("%v", td{1, nil}))
}
▸ go run main.go
{1}
{1 <nil>}
%!v(PANIC=runtime error: invalid memory address or nil pointer dereference)
{1 <nil>}
https://play.golang.org/p/SrzUsJ3pyRC https://play.golang.org/p/SrzUsJ3pyRC
Follow up question: if I have such a value tc{1, nil}
, how to print it without causing panic? 跟进问题:如果我有
tc{1, nil}
这样的值,如何打印而不会引起恐慌?
In tc
, you're embedding a value of type error
. 在
tc
,您要嵌入类型为error
的值。 Sprintf
sees that tc
implements error
(because of embedding), and tries to call Error()
on it, which triggers the error because the value is nil
. Sprintf
看到tc
实现了error
(由于嵌入),并尝试在其上调用Error()
,这会触发错误,因为该值为nil
。
If you want to print it without causing a panic, don't embed error
(put it in a named field), or make sure the embedded error
value is not nil
. 如果要打印而不会引起紧急情况,请不要嵌入
error
(将其放在命名字段中),或确保嵌入的error
值不是nil
。
I don't know why, but this seems to fix it ... 我不知道为什么,但这似乎可以解决...
type tc struct {
Num int
Err error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.