Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function on element of struct which is a nil pointer

Tags:

struct

go

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.

like image 207
Prakash P Avatar asked Mar 12 '26 04:03

Prakash P


1 Answers

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

like image 61
Yates Xing Avatar answered Mar 15 '26 03:03

Yates Xing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!