Three things about the map data type in Go

  • 2020-05-05 11:22:58
  • OfStack

1, map data type initializes

Two ways: map[string]string{} or make(map[string]string)

2, uninitialized map is nil , which is basically equivalent to an empty map, except map of nil does not allow values to be added to it. A nil map is equivalent to empty except that no elements be added)

Therefore, when map is nil, the value will not be wrong (it cannot be taken), but the value added will be wrong.

In fact, there is another difference, delete an nil map will panic, but delete empty map is an empty operation (not panic) (this difference has been eliminated in the latest Go tips, delete an nil map will not panic)

3. When map is printed by fmt, map and nil map are both map[]. So, don't decide whether map is empty or nil, but map == nil.

This is true of the Form field in Request, where ParseForm() is not called directly or indirectly, Form is actually nil, but you might be confused if println comes out as map[]. By tracing the source code, you can see that Form is not initialized at all. The FormValue() method determines whether Form is nil, and then decides whether to call the ParseForm() method. Of course, you can also call the ParseForm() method manually.


Related articles: