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