【go学习笔记】八、Map与工厂模式

Map与工厂模式

  • Map的value可以是一个方法
  • 与Go的Dock type 接口方式一起,可是方便的实现单一方法对象的工厂模式
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))
}

输出

=== RUN   TestMap
--- PASS: TestMap (0.00s)
    map_test.go:10: 2 4 8
PASS

Process finished with exit code 0

实现 Set

Go的内置集合中没有Set实现,可以map[type]bool

  1. 元素的唯一性
  2. 基本操作
  • 添加元素
  • 判断元素是否存在
  • 删除元素
  • 元素个数
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)
	}
}

输出

=== 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 0

示例代码请访问: https://github.com/wenjianzhang/golearning

原文地址:https://www.cnblogs.com/zhangwenjian/p/12527355.html