Learn Golang in Days - Day 12
要点
- Map是一种无序的键值对的集合。Map最重要的一点是通过Key可以检索到Valu.
- Map是使用hash表来实现的
定义map
- 使用map关键字定义
- 使用make函数定义
// 声明变量,默认map是nil
var map_variable map[key_data_type]value_data_type
var countryMap map[string]string
// 使用make函数来定义
map_variable := make(map[key_data_type]value_data_type)
countryMap := make(map[string]string)
//定义并初始化
var countryMap := map[string]string{"Janpa":"Tokyo","USA":"Washington D.C."}
实例
import "fmt"
func main() {
// 定义map
var countrycapitalmap map[string]string
countrycapitalmap = make(map[string]string)
countrycapitalmap["france"] = "pairs"
countrycapitalmap["italy"] = "roma"
countrycapitalmap["japan"] = "tokya"
//遍历输出
for counry := range countrycapitalmap {
fmt.Printf("countrymap[\"%s\"]=%s\n", counry, countrycapitalmap[counry])
}
// 查看元素是否在集合中存在
capital ,ok := countrycapitalmap["france"]
if(ok){
fmt.Printf("法国的首都是%s\n", capital)
}else{
fmt.Printf("集合中未找到寻找的键\n")
}
capital ,ok = countrycapitalmap["德国"]
if(ok){
fmt.Printf("德国的首都是%s\n", capital)
}else{
fmt.Printf("集合中未找到寻找的键德国\n")
}
}
delete() 函数,删除元素
- delete() 函数删除集合中的元素,参数为map和其对应的键
- delete(Map, item)
package main
import "fmt"
func main() {
// 定义map
var countryMap map[string]string
countryMap = make(map[string]string)
countryMap1 := map[string]string{"Japan": "Tokyo", "China": "Beijing"}
countryMap["Japan"] = "Tokyo"
//遍历
fmt.Println("------ 删除前 遍历 -----------")
for country := range countryMap1 {
fmt.Printf("countryMap1[%s]=%s\n", country, countryMap1[country])
}
// 删除元素
delete(countryMap1, "China")
//遍历
fmt.Println("------ 删除后 遍历 -----------")
for country := range countryMap1 {
fmt.Printf("countryMap1[%s]=%s\n", country, countryMap1[country])
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Building Social Web Applications
Gavin Bell / O'Reilly Media / 2009-10-1 / USD 34.99
Building a social web application that attracts and retains regular visitors, and gets them to interact, isn't easy to do. This book walks you through the tough questions you'll face if you're to crea......一起来看看 《Building Social Web Applications》 这本书的介绍吧!