当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > 【go学习笔记】八、Map与工厂模式

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

2020年03月20日  | 移动技术网IT编程  | 我要评论

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

示例代码请访问:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网