Map declaration
m := map[string]int{
"one": 1, "two": 2, "three": 3}
m1 := map[string]int{
}
m1["one"] = 1
m2 := make(map[string]int, 10 /*Initial Capacity*/)
func TestInitMap(t *testing.T) {
m1 := map[int]int{
1: 1, 2: 4, 3: 9}
t.Log(m1[2])
t.Logf("len m1=%d", len(m1))
m2 := map[int]int{
}
m2[5] = 16
t.Logf("len m2=%d", len(m2))
m3 := make(map[int]int, 10)
t.Logf("len m3=%d", len(m3))
}
Access to Map elements
Differences from other major programming languages
When the accessed Key does not exist, a zero value will still be returned, and nil cannot be returned to determine whether an element exists
if v, ok := m["four"]; ok {
t.Log("four", v)
} else {
t.Log("Not existing")
}
// map不存在key测试 不存在key 取值为0, 判断是否存在key ok:=m1[3]
func TestAccessNotExistingKey(t *testing.T) {
m1 := map[int]int{
}
t.Log(m1[1])
m1[2] = 0
t.Log(m1[2])
m1[3] = 0
// v, ok:=m1[3]; v: m1[3] ok: 判断map是否存在该key 存在返回true 反之false
if v, ok := m1[3]; ok {
t.Logf("Key 3 value is %d", v)
} else {
t.Logf("Key 3 is not existing")
}
}
Map traversal
// map 遍历
func TestTravelMap(t *testing.T) {
m1 := map[int]int{
1: 2, 2: 4, 3: 8, 4: 16}
for k, v := range m1 {
t.Log(k, v)
}
}
Map and factory pattern
- The value of Map can be a method
- Together with Go's Dock type interface, it is convenient to implement the factory pattern of a single method object
Implement Set
There is no Set implementation in Go's built-in collection, you can map[type]bool
- uniqueness of elements
- basic operation
- add element
- Determine whether an element exists
- delete element
- number of elements
package _map
import "testing"
// - Map的value可以是一个方法
func TestMapWithFunValue(t *testing.T) {
m := map[int]func(op int) int{
}
m[1] = func(op int) int {
return op
}
m[2] = func(op int) int {
return op * op
}
m[3] = func(op int) int {
return op * op * op
}
t.Log(m[1](1), m[2](2), m[3](3))
}
// set
func TestMapForSet(t *testing.T) {
mSet := map[int]bool{
}
mSet[1] = true
//n := 1 // map_ext_test.go:27: 1 is existing
n := 3 // map_ext_test.go:30: 3 is not existing
if mSet[n] {
t.Logf("%d is existing", n)
} else {
t.Logf("%d is not existing", n)
}
mSet[3] = true
t.Log(len(mSet)) // map_ext_test.go:33: 2
delete(mSet, 1)
n = 1 // map_ext_test.go:39: 1 is not existing
if mSet[n] {
t.Logf("%d is existing", n)
} else {
t.Logf("%d is not existing", n)
}
}
PS: study notes, invade and delete!