In Go, however, 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 - copied
So we can call a method
using a struct instance which is nil.
Consider the following program:
package main
import "fmt"
type T struct {
V int
tt *T
}
func (t *T) hello() string {
return "world"
}
func main() {
var t *T = nil
fmt.Println(t, t.hello()) // <nil> world
fmt.Println(t, t.tt.hello()) // panic
}
Why fmt.Println(t, t.hello())
worked?
But
fmt.Println(t, t.tt.hello())
panicked?.
My understanding is that both t
and t.tt
are nil
pointers. So t.tt.hello()
should not panic as Calling a method on a nil struct pointer is allowed in golang.