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
}
有疑问加站长微信联系(非本文作者)