zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    exp 和imp 与expdp / impdp 区别
    nginx优化
    nginx root alias proxypass
    mysql3
    logrotate 用法
    SQL执行顺序
    http与RPC的关系
    docker
    windows 时间同步
    Java生成指定长度的随机字符串
  • 原文地址:https://www.cnblogs.com/zhangwenjian/p/12527355.html
Copyright © 2011-2022 走看看