Sobes.tech
Junior — Middle

Can nil be used as an iteration element for a map in a loop?

sobes.tech AI

Answer from AI

In Go, the value nil cannot be used as an iteration element for a map in a loop because range over a map returns a key and a value, and nil is the absence of a value.

If the value in the map is a pointer or an interface, it can be nil, and that is normal. But the iterator itself cannot be nil.

Example:

m := map[string]*int{
    "a": nil,
    "b": new(int),
}

for k, v := range m {
    if v == nil {
        fmt.Printf("Key %s contains a nil value\n", k)
    } else {
        fmt.Printf("Key %s contains value %d\n", k, *v)
    }
}

Here, v can be nil, but the range loop over the map works correctly.