preface

There are still two hours left before I can leave work, and I feel a little guilty watching the time pass by. In order not to let myself have too deep guilt, THEN I will write another article.

Fish days are so dry……

Go in the nil

The word nil means “zero” or “nothing,” and in Go, nil means a zero value.

In Go, if we declare a variable but do not assign a value to it, the variable is a “zero”, as when we declare an integer int.

    var a int
    fmt.Printf("this is a %v",a) // this is a 0
Copy the code

Strings, in the same case, default to null characters. And so on, if a pointer doesn’t explicitly point to anything, its value is also nil.

In Go, nil is very friendly, for reasons I’ll explain below.

A pointer to nil

We know that when a pointer doesn’t have an explicit point to it, it’s nil, and programs that dereference a nil pointer will crash.

    var a * int
    fmt.Println(a) // nil
    fmt.Println(*a) 
    // panic: runtime error: invalid memory address or nil pointer dereference
Copy the code

And to avoid this situation, it is also very simple, just need to dereference the pointer, add a judgment can be

type person struct {
	num int
}

func (p *person) change(a)  {
        if p == nil {
            return
        }
        p.num++
}

func main(a) {
	p := person{10}
	p.change()
	fmt.Printf("this is num %+v",p) 
        // this is num {num:11}
}
Copy the code

In Go, the handling of nil is up to the developer to decide whether to return zero, an error type, or panic.

Nil slicing and mapping

When a slice or map is declared, it will also be nil if it is not initialized with a compound literal or the built-in make function.

    var a []int
    fmt.Print(a == nil) // true
Copy the code

As mentioned earlier, if you try to manipulate nil, the program will report an error, but the nice thing is that the three functions we use to handle slicing or mapping, Append, Len, and Ranger, all have built-in methods to handle nil

    var a []int
    fmt.Print(a == nil) // true

    for v := range a{
            fmt.Print(v)
    }

    fmt.Print(len(a)) / / 0

    a = append(a, 1.2.3.4) 
    fmt.Print(a) / / [1, 2, 3, 4]
Copy the code

The last

Although nil can sometimes be a little bit problematic when you use it, it can be useful in some special cases, like when you use select, which I’ll talk about in a future article, but that’s it for today.

Come off work, yo-yo 🪀!!