From 2470d058727e0838167914c40cf258c8a457b78e Mon Sep 17 00:00:00 2001 From: cui fliter Date: Tue, 10 Oct 2023 10:51:19 +0800 Subject: [PATCH] maps: add examples for Clone,Copy and Equal Change-Id: I72adaf48588e7d6cffbc0ee8005decda06808e84 Reviewed-on: https://go-review.googlesource.com/c/go/+/534055 TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Run-TryBot: shuang cui Reviewed-by: Dmitri Shuralyov Auto-Submit: Ian Lance Taylor --- src/maps/example_test.go | 90 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/src/maps/example_test.go b/src/maps/example_test.go index 779c66dcef..3d6b7d1ba0 100644 --- a/src/maps/example_test.go +++ b/src/maps/example_test.go @@ -10,6 +10,72 @@ import ( "strings" ) +func ExampleClone() { + m1 := map[string]int{ + "key": 1, + } + m2 := maps.Clone(m1) + m2["key"] = 100 + fmt.Println(m1["key"]) + fmt.Println(m2["key"]) + + m3 := map[string][]int{ + "key": {1, 2, 3}, + } + m4 := maps.Clone(m3) + fmt.Println(m4["key"][0]) + m4["key"][0] = 100 + fmt.Println(m3["key"][0]) + fmt.Println(m4["key"][0]) + + // Output: + // 1 + // 100 + // 1 + // 100 + // 100 +} + +func ExampleCopy() { + m1 := map[string]int{ + "one": 1, + "two": 2, + } + m2 := map[string]int{ + "one": 10, + } + + maps.Copy(m2, m1) + fmt.Println("m2 is:", m2) + + m2["one"] = 100 + fmt.Println("m1 is:", m1) + fmt.Println("m2 is:", m2) + + m3 := map[string][]int{ + "one": {1, 2, 3}, + "two": {4, 5, 6}, + } + m4 := map[string][]int{ + "one": {7, 8, 9}, + } + + maps.Copy(m4, m3) + fmt.Println("m4 is:", m4) + + m4["one"][0] = 100 + fmt.Println("m3 is:", m3) + fmt.Println("m4 is:", m4) + + // Output: + // m2 is: map[one:1 two:2] + // m1 is: map[one:1 two:2] + // m2 is: map[one:100 two:2] + // m4 is: map[one:[1 2 3] two:[4 5 6]] + // m3 is: map[one:[100 2 3] two:[4 5 6]] + // m4 is: map[one:[100 2 3] two:[4 5 6]] +} + func ExampleDeleteFunc() { m := map[string]int{ "one": 1, @@ -25,6 +91,30 @@ func ExampleDeleteFunc() { // map[four:4 two:2] } +func ExampleEqual() { + m1 := map[int]string{ + 1: "one", + 10: "Ten", + 1000: "THOUSAND", + } + m2 := map[int]string{ + 1: "one", + 10: "Ten", + 1000: "THOUSAND", + } + m3 := map[int]string{ + 1: "one", + 10: "ten", + 1000: "thousand", + } + + fmt.Println(maps.Equal(m1, m2)) + fmt.Println(maps.Equal(m1, m3)) + // Output: + // true + // false +} + func ExampleEqualFunc() { m1 := map[int]string{ 1: "one", -- 2.50.0