Latest web development tutorials

이동 언어지도 (컬렉션)

지도는 키의 무질서 모음입니다. 가장 중요한 것은 신속하게 데이터의 값으로 키와 유사한 키 인덱스, 점 데이터를 검색하는 것입니다지도.

지도 모음입니다, 그래서 우리는 반복 반복 배열과 조각으로 그것을 좋아하지 수 있습니다. 그러나,지도 무질서한 맵 달성하기 위해 해시 테이블을 사용하기 때문에, 우리는 반환 순서를 결정할 수이다.

정의지도

또한지도지도 키워드를 사용하여 정의 할 수 있습니다 내장 함수를 사용할 수있다 :

/* 声明变量,默认 map 是 nil */
var map_variable map[key_data_type]value_data_type

/* 使用 make 函数 */
map_variable = make(map[key_data_type]value_data_type)

당신이지도를 초기화하지 않는 경우는 전무 맵을 생성합니다. 무 맵은 키 - 값 쌍을 저장하는 데 사용될 수 없다

다음의 예는지도의 작성 및 사용하는 방법을 보여줍니다 :

package main

import "fmt"

func main() {
   var countryCapitalMap map[string]string
   /* 创建集合 */
   countryCapitalMap = make(map[string]string)
   
   /* map 插入 key-value 对,各个国家对应的首都 */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
   
   /* 使用 key 输出 map 值 */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* 查看元素在集合中是否存在 */
   captial, ok := countryCapitalMap["United States"]
   /* 如果 ok 是 true, 则存在,否则不存在 */
   if(ok){
      fmt.Println("Capital of United States is", captial)  
   }else {
      fmt.Println("Capital of United States is not present") 
   }
}

위의 운영 결과의 예는 다음과 같습니다 :

Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Capital of United States is not present

삭제 () 함수

컬렉션의 요소는 기능은지도와 해당 키에 대한 매개 변수를 삭제하는 데 사용됩니다 () 삭제합니다. 다음 예는 다음과 같다 :

package main

import "fmt"

func main() {   
   /* 创建 map */
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
   
   fmt.Println("原始 map")   
   
   /* 打印 map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* 删除元素 */
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")  
   
   fmt.Println("删除元素后 map")   
   
   /* 打印 map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
}

위의 운영 결과의 예는 다음과 같습니다 :

原始 map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
删除元素后 map
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi