From 0812429584978a95f3d4475011695608a2d95d88 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 20 Mar 2023 05:59:53 -0700 Subject: [PATCH] Clarify zero value for map values when keys don't exist --- examples/maps/maps.go | 8 +++++++- examples/maps/maps.hash | 4 ++-- examples/maps/maps.sh | 3 ++- public/maps | 25 +++++++++++++++++++++---- 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/examples/maps/maps.go b/examples/maps/maps.go index 8a40d35..441e2a3 100644 --- a/examples/maps/maps.go +++ b/examples/maps/maps.go @@ -22,7 +22,13 @@ func main() { // Get a value for a key with `name[key]`. v1 := m["k1"] - fmt.Println("v1: ", v1) + fmt.Println("v1:", v1) + + // If the key doesn't exist, the + // [zero value](https://go.dev/ref/spec#The_zero_value) of the + // value type is returned. + v3 := m["k3"] + fmt.Println("v3:", v3) // The builtin `len` returns the number of key/value // pairs when called on a map. diff --git a/examples/maps/maps.hash b/examples/maps/maps.hash index 2c0cd81..9dcd6b8 100644 --- a/examples/maps/maps.hash +++ b/examples/maps/maps.hash @@ -1,2 +1,2 @@ -22d147fe9402f9ff210f12b9810811c07f4d64ca -ulCzODwCde_0 +0d764945481b4960c573e67f7d303166b750413e +xl_teZEVqbo diff --git a/examples/maps/maps.sh b/examples/maps/maps.sh index da7a841..56f3be1 100644 --- a/examples/maps/maps.sh +++ b/examples/maps/maps.sh @@ -2,7 +2,8 @@ # printed with `fmt.Println`. $ go run maps.go map: map[k1:7 k2:13] -v1: 7 +v1: 7 +v3: 0 len: 2 map: map[k1:7] prs: false diff --git a/public/maps b/public/maps index bf99e93..8e64a84 100644 --- a/public/maps +++ b/public/maps @@ -42,7 +42,7 @@ - +
package main
 
@@ -122,7 +122,23 @@ its key/value pairs.

     v1 := m["k1"]
-    fmt.Println("v1: ", v1)
+    fmt.Println("v1:", v1)
+
+ + + + + +

If the key doesn’t exist, the +zero value of the +value type is returned.

+ + + + +
+    v3 := m["k3"]
+    fmt.Println("v3:", v3)
 
@@ -207,7 +223,8 @@ printed with fmt.Println.

 $ go run maps.go 
 map: map[k1:7 k2:13]
-v1:  7
+v1: 7
+v3: 0
 len: 2
 map: map[k1:7]
 prs: false
@@ -230,7 +247,7 @@ printed with fmt.Println.