Test code ( https://play.golang.org/p/z__pwPlGxAT ):
package main
import (
"fmt"
)
func test(i interface{}){
switch i.(type) {
case error:
fmt.Printf("error type\n")
default:
fmt.Printf("other type\n")
}
fmt.Printf("%v\n", i)
}
func main() {
i1 := struct {
string
error
}{ "a", nil }
fmt.Println("--------- case 1 ---------")
test(i1)
i2 := struct {
S string
error
}{ "a", nil }
fmt.Println("--------- case 2 ---------")
test(i2)
i3 := struct {
string
E error
}{ "a", nil }
fmt.Println("--------- case 3 ---------")
test(i3)
}
Output:
--------- case 1 ---------
error type
%!v(PANIC=runtime error: invalid memory address or nil pointer dereference)
--------- case 2 ---------
error type
%!v(PANIC=runtime error: invalid memory address or nil pointer dereference)
--------- case 3 ---------
other type
{a <nil>}
Conclusion
If an anonymous struct with a error field but without give the field a name, the Printf('%v')
will process this struct as an error
type, but the error
field is nil, Printf
will call error.Error()
to print its value, so we got an runtime error: invalid memory address or nil pointer dereference
error message.