type MyError struct {
errors []string
}
func (t *MyError) Error() string {
if t == nil {
fmt.Println("t ptr empty")
return ""
}
pointers := make([]string, 0, len(t.errors))
for i, r := range t.errors {
pointers[i] = r
}
sort.Strings(pointers)
return fmt.Sprintf("n error(s) decoding:\n\n%s", len(t.errors), strings.Join(pointers, ","))
}
func main() {
var err *MyError
err.Error() // expected "panic: runtime error: invalid memory address or nil pointer dereference" here
}
變量err爲零,所以調用err.Error()方法應該會導致恐慌「運行時錯誤:無效的內存地址或零指針取消引用」,但方法調用成功。爲什麼不這麼恐慌?在零結構指針上調用方法不會驚慌。爲什麼不?
因爲語言規範是這樣說的嗎? – Volker