SoFunction
Updated on 2025-03-05

Golang Tongmai map details

The mapping relation container provided in Go language ismap, which is implemented internally using a hash table (hash).

map is an unordered set of key-value pairs. The most important thing about map is to quickly retrieve data through keys.key Similar to an index, the value map pointing to the data is a collection, so it can be iterated over it like iterating over an array and slice. However, map is unordered and cannot determine its return order. This is because map is implemented using a hash table. Maps in Go are reference types and must be initialized to use.

Some points to note during the use of map:

  • Map is unordered, and the map printed will be different every time. It cannot be obtained through index, but must be obtained through key
  • The length of the map is not fixed, which means that it is a reference type, just like slice.
  • The built-in len function is also applicable to map, returning the number of keys that map has
  • The map key can be allComparison type, such as Boolean, integer, floating point, complex, string... can also be keyed.

1. Definition

The definition syntax of map in Go language is as follows:

map[KeyType]ValueType

in

  • KeyType: indicates the type of key.
  • ValueType: represents the type of value corresponding to the key.

**mapThe default initial value of a variable of type isnil, need to usemake()Function to allocate memory (declare and initialize) **.

The syntax is:

make(map[KeyType]ValueType, [cap])

Where cap represents the capacity of the map. Although this parameter is not necessary, we should specify a suitable capacity for the map when initializing it.

You can use the built-in function make or use the map keyword to define Map:

/* declare variables, the default map is nil */
var mapVariable map[KeyType]ValueType
 
/* Use make function */
mapVariable = make(map[keyType]ValueType)
rating := map[string]float32 {"C":5, "Go":4.5, "Python":4.5, "C++":2 }


If not initializedmap, then anil mapnil map Can't be used to store key-value pairs

2. Basic use

The data in the map all appear in pairs:

func main() {
 scoreMap := make(map[string]int, 8)
 scoreMap["Zhang San"] = 90
 scoreMap["Xiao Ming"] = 100
 (scoreMap)
 (scoreMap["Xiao Ming"])
 ("type of a:%T\n", scoreMap)
}

Output:

map[Xiao Ming:100 Zhang San:90]
100
type of a:map[string]int

Map also supports filling elements when declared, for example:

func main() {
 userInfo := map[string]string{
  "username": "Zhang San",
  "password": "123456",
 }
 (userInfo) //
}

3. Determine whether the key exists

There is a special way to determine whether the keys in map exist in Go language, the format is as follows:

value, ok := map[key]
func main() {
 /* Create a collection */
   countryCapitalMap := make(map[string]string)
   
   /* map insert key-value pair, the corresponding capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 // If the key exists that ok is true, v is the corresponding value; if ok is false, v is the zero value of the value type v, ok := countryCapitalMap["United States"]
 if ok {
  ("Capital of United States is", captial)  
   }else {
      ("Capital of United States is not present") 
   }
}

4. Map traversal

Used in Gofor rangeTraversalmap

func main() {
 countryCapitalMap := make(map[string]string)
   /* map insert key-value pair, the corresponding capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 for k, v := range countryCapitalMap {
  (k, v)
 }
}

When you just want to traverse the key, you can write it as follows:

func main() {
 countryCapitalMap := make(map[string]string)
   /* map insert key-value pair, the corresponding capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 for k := range countryCapitalMap {
  (k)
 }
}

Notice:The order of elements when traversing the map has nothing to do with the order in which key-value pairs are added.

5. Delete() function deletes map element

usedelete()Built-in functions frommapDelete a set of key-value pairs in it, and the delete function does not return any value.delete()The format of the function is as follows:

delete(map, key)

in,

  • map: Indicates the map to delete the key-value pair
  • key: The key indicating the key-value pair to be deleted
func main(){
 countryCapitalMap := make(map[string]string)
   /* map insert key-value pair, the corresponding capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 delete(countryCapitalMap, "France")//Remove "France":"Paris" from the map for k,v := range scoreMap{
  (k, v)
 }
}

6. Specify the order of traversal of maps

func main() {
 (().UnixNano()) //Initialize random number seed 
 var scoreMap = make(map[string]int, 200)
 
 for i := 0; i < 100; i++ {
  key := ("stu%02d", i) //Generate strings starting with stu  value := (100)          // Generate random integers from 0 to 99  scoreMap[key] = value
 }
 //Take out all keys in the map and store them into slice keys var keys = make([]string, 0, 200)
 for key := range scoreMap {
  keys = append(keys, key)
 }
 //Sort the slices (keys)
 //Travel the map by the sorted key for _, key := range keys {
  (key, scoreMap[key])
 }
}

7. Map type slice

The following code is the operation when the element in the slice is of map type:

func main() {
 var mapSlice = make([]map[string]string, 3)
 for index, value := range mapSlice {
  ("index:%d value:%v\n", index, value)
 }
 ("after init")
 // Initialize the map element in the slice mapSlice[0] = make(map[string]string, 10)
 mapSlice[0]["username"] = "Zhang San"
 mapSlice[0]["password"] = "123456"
 mapSlice[0]["address"] = "Shenzhen"
 for index, value := range mapSlice {
  ("index:%d value:%v\n", index, value)
 }
}

8. The value is the map of the slice type

The following code demonstrates the operation of the value of the map as a slice type:

func main() {
 var sliceMap = make(map[string][]string, 3)
 (sliceMap)
 ("after init")
 key := "China"
 value, ok := sliceMap[key]
 if !ok {
  value = make([]string, 0, 2)
 }
 value = append(value, "Beijing", "Shanghai")
 sliceMap[key] = value
 (sliceMap)
}

9. Map is a reference type

Similar to slices,mapis a reference type. WhenmapWhen assigned to a new variable, they all point to the same internal data structure. therefore,Changes in one will reflect the other:

func main() {  
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    ("Original person salary", personSalary)
    newPersonSalary := personSalary
    newPersonSalary["mike"] = 18000
    ("Person salary changed", personSalary)
 
}

Running results:

Original person salary map[steve:12000 jamie:15000 mike:9000] 
Person salary changed map[steve:12000 jamie:15000 mike:18000]

Map cannot be compared using operators. It can only be used to check whether the map is empty. Otherwise, an error will be reported:invalid operation: map1 == map2 (map can only be comparedto nil)

This is the end of this article about the detailed map of Golang Tongmai. For more related Golang map content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!