Avatar ·

What is null/nil in Go and how to work with it?

Hello everyone! I started learning Go and encountered the concept of nil. In other languages (e.g., Java or JavaScript) there is null, which often causes errors (NullPointerException). In Go, as I understand, nil is used, but the behavior is different.

Here's what I tried:

package main\n\nimport "fmt"\n\nfunc main() {\n    var p *int\n    fmt.Println(p) // prints nil\n    // fmt.Println(*p) // panic: runtime error: invalid memory address or nil pointer dereference\n    \n    var s []int\n    fmt.Println(s == nil) // true\n    fmt.Println(len(s))   // 0\n    // s[0] = 1 // panic\n    \n    var m map[string]int\n    fmt.Println(m == nil) // true\n    // m["key"] = 1 // panic\n}\n

Questions:

  1. Why does nil