duanhui3759 2017-02-15 00:15
浏览 40

在nil struct指针上调用方法不会引起恐慌。 为什么不?

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:

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

The variable err is nil so calling err.Error() method is expected to cause a panic "runtime error: invalid memory address or nil pointer dereference", but the method call succeeds. Why doesn't this panic?

  • 写回答

2条回答 默认 最新

  • dqqpf32897 2017-02-15 01:00
    关注

    Please read: https://golang.org/ref/spec#The_zero_value

    When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

    So in your code, var err *MyError is nil, you can call err.Error() is ok even err = nill,

    **

    In Go, the function to be called by the Expression.Name() syntax is entirely determined by the type of Expression and not by the particular run-time value of that expression, including nil.

    **

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作