Map and factory patterns
- The value of a 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
func TestMap(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] (2), m[2] (2), m[3] (2))}Copy the code
The output
=== RUN TestMap -- PASS: TestMap (0.00s) map_test.go:10: 2 4 8 PASS Process finished with exit code 0Copy the code
To achieve the Set
There is no Set implementation in Go’s built-in collection, map[type]bool can be used
- Uniqueness of elements
- Basic operation
- Add elements
- Determines whether the element exists
- Remove elements
- Number of elements
func TestMapForSet(t *testing.T) {
mySet := map[int]bool{}
mySet[1] = true
n := 3
if mySet[n] {
t.Logf("%d is existing", n)
} else {
t.Logf("%d is not existing", n)
}
mySet[3] = true
t.Log(len(mySet))
delete(mySet,1)
n = 1
if mySet[n] {
t.Logf("%d is existing", n)
} else {
t.Logf("%d is not existing", n)
}
}
Copy the code
The output
=== RUN TestMapForSet -- PASS: TestMapForSet (0.00s) map_test.go:20: 3 is not existing map_test.go:23: 2 map_test.go:29: 1 is not existing PASS Process finished with exit code 0Copy the code
Sample code can be found at: github.com/wenjianzhan…