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.
t is nil,there is no t.tt.
And t.hello() is like hello(t), hello(nil) don't panic, but t.tt do.
Remember: a method is just a function with a receiver argument.
Method expressions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With