1

Hello everyone, I am fried fish.

Recently, in our Go technical exchange group, a small partner raised a procedural question, which is quite interesting. Share it with everyone.

Example

The sample program is as follows:

type T struct{}

func (t *T) Hello() string {
    if t == nil {
        fmt.Println("脑子进煎鱼了")
        return ""
    }

    return "煎鱼进脑子了"
}

func main() {
    var t *T
    t.Hello()

What is the result of this program?

From the analysis of the program, the variable t is not initialized, but the type is declared. Hello method is directly called, such as nil calling the function, theoretically there should be panic.

The result of the operation is:

panic: runtime error: invalid memory address or nil pointer dereference

Right?

Obviously, the real operating result is:

脑子进煎鱼了

Please think about it and think about why?

Why

The reason for the problem is that many friends think that t is all nil, and it shouldn't be called.

More abstractly speaking, it is "how does the program check the object pointer to find and dispatch the required function".

In fact, in Go, Expression.Name , the function called is completely determined by the type of Expression

The direction of the calling function is not determined by the specific runtime value of the expression, including the nil we mentioned earlier.

details as follows:

func (p *Sometype) Somemethod (firstArg int) {}

Essentially:

func SometypeSomemethod(p *Sometype, firstArg int) {}

Looking at it this way, in fact, everyone should understand.

The above-mentioned p *Sometype parameter 061ce8e5bdf75c has a specific context type, and the corresponding method can be called naturally. If there is no context type, for example: nil.Somemethod method to call, it must be unable to run.

And whether the value is nil or not has much direct influence on what it is. As long as there is a context of the expected type.

Summarize

Today I shared with you a small detail in the Go language, which may not be noticed by many people. After all, the IDE will also be yellow and will avoid this problem.

In understanding the design and thinking of Go, we need to be clear about the reason and logic behind it, that is, the type determines the call, not the value (easy to misjudge).

Have you encountered any other detailed problems? Welcome to communicate:)

If you have any questions, welcome feedback and exchanges in the comment area. The best relationship between . Your likes is the biggest motivation for the creation of fried fish

Article continually updated, you can head into the micro-channel search [fried] read the article GitHub github.com/eddycjy/blog already been included, Go language learning can be seen Go Learning Map and Directions , welcome Star urge more.

煎鱼
8.4k 声望12.8k 粉丝