Golang学习笔记-map

map是一些键值对的集合,默认值为nil,使用内置函数make创建map:

var map_variable map[key_data_type]value_data_type
map_variable := make(map[key_data_type]value_data_type)
func main() {
    var numberMap map[string] int
    numberMap=make(map[string]int)
    println(len(numberMap))
}

map可以使用大括号来初始化:

var numberMap =map[string] int{"one":1,"two":2,"three":3}

判断元素是否存在:

func main() {
    var numberMap =map[string] int{"one":1,"two":2,"three":3}
    number,ok:=numberMap["four"]
    if ok{
        println(number)
    }else{
        println("key four not exists")
    }
}

添加和删除元素:

func main() {
    var numberMap =map[string] int{"one":1,"two":2,"three":3}
    println(numberMap["one"])//1
    println(numberMap["four"])//0
    //添加一个key-value
    numberMap["four"]=4
    println(numberMap["four"])//4
    //删除一个key-value
    delete(numberMap,"four")
    println(numberMap["four"])//0
}

map的遍历顺序是不固定的,运行下面的代码会发现有时候遍历的顺序不是1234。

func main(){
	var numberMap =map[string] int{"one":1,"two":2,"three":3,"four":4}

	for i:=0;i<100;i++{
		fmt.Println("==========================")
		for k,v:=range numberMap{
			fmt.Printf("%s=>%d\n",k,v)
		}
	}
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页