Go语言gomap模块获取map的keys切片

gomap模块定制了一组常用的map[K]V类型,主要是为了增加GetKeys() ([]K)方法,执行效率和单独写GetKeys方法是一样的。因为Go 1.x不能支持泛型,所以只实现了6种常用的map[K]V。

实现原理:

type StringBoolMap map[string]bool

func (m StringBoolMap) GetKeys() []string {
	j := 0
	keys := make([]string, len(m))
	for k := range m {
		keys[j] = k
		j++
	}
	return keys
}

使用方法:

package main

import (
	"fmt"
	"github.com/pochard/gomap"
)


func main(){
	sbmap := make(gomap.StringBoolMap)
	sbmap["China"] = true
	sbmap["USA"] = true
 	sbmap["Japan"] = true

	fmt.Printf("StringBoolMap keys:\n")
	for _,key := range sbmap.GetKeys(){
 		fmt.Printf("%s\n", key)
 	}

	ssmap := make(gomap.StringStringMap)
	ssmap["China"] = "Chinese"
	ssmap["USA"] = "English"
 	ssmap["Japan"] = "Japanese"

	fmt.Printf("StringStringMap keys:\n")
	for _,key := range ssmap.GetKeys(){
 		fmt.Printf("%s\n", key)
 	}

	simap := make(gomap.StringIntMap)
	simap["China"] = 145
	simap["USA"] = 6756
	simap["Japan"] = 987

	fmt.Printf("StringIntMap keys:\n")
	for _,key := range simap.GetKeys(){
		fmt.Printf("%s\n", key)
	}

	ismap := make(gomap.IntStringMap)
	ismap[145] = "China"
	ismap[6756] = "USA"
	ismap[987] = "Japan"

	fmt.Printf("IntStringMap keys:\n")
	for _,key := range ismap.GetKeys(){
		fmt.Printf("%d\n", key)
	}

	iimap := make(gomap.IntIntMap)
	iimap[145] = 12
	iimap[6756] = 24
	iimap[987] = 32

	fmt.Printf("IntIntMap keys:\n")
	for _,key := range iimap.GetKeys(){
		fmt.Printf("%d\n", key)
	}

	ibmap := make(gomap.IntBoolMap)
	ibmap[145] = true
	ibmap[6756] = true
	ibmap[987] = true

	fmt.Printf("IntBoolMap keys:\n")
	for _,key := range ibmap.GetKeys(){
		fmt.Printf("%d\n", key)
	}
}

 

你可能感兴趣的:(go)