Basic use of map data type in Go language

Map

Basic syntax:

var map variable name map[keytype][valuetype]

Note: The declaration will not allocate memory, the initialization requires make, and the memory can be assigned and used after allocating

Precautions:

  • map must make before use
  • The key of the map cannot be repeated. If it is repeated, the last one shall prevail.
  • The key-value of map is unordered
  • number of make built-in functions

How to use:

func  main ( ) { 
	// mode 1 
	var a map [ string ] int  
	a =  make ( map [ string ] int , 10 ) 
	a [ "ywh" ]  =  21 
	a [ "wl" ]  =  22 
	fmt . Println ( a ) 
	// way 2 
	cites :=  make ( map [ string ] string )
	cites [ "beijing" ]  =  "0123" 
	cites [ "shanghai" ]  =  "34828" 
	fmt . Println ( cites ) 
	// mode 3 
	b :=  map [ string ] string { 
		"a" : "ywh" , 
		"b" : "wl" , 
	} 
	fmt . Println ( b ) 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

Add, delete, modify and check the map

Additions:

map[key] = value, if the key does not exist, it will be added, if there is, it will be modified

delete:

delete(map,key), delete the key-value whose key is key in the map

Mmap = make(map[string][string]), if you want to delete all of them directly, you can define a new map between them, so that the original one becomes garbage and is recycled by GC

Find:

if val , ok := mmap [ "ywh" ] ; ok { 
	//... 
} else { 
	//... 
}
  • 1
  • 2
  • 3
  • 4
  • 5

Traversal of map:

for k , v :=  range cites { 
    fmt . Printf ( "k=%v,val=%v" , k , v ) 
}
  • 1
  • 2
  • 3

map can also be used as a data type for slices:

func  main ( ) { 
	fruits :=  make ( [ ] map [ string ] string , 2 ) 
	if fruits [ 0 ] == nil { 
		fruits [ 0 ]  =  make ( map [ string ] string ,  2 ) 
		fruits [ 0 ] [ " name" ]  =  "apple" 
		fruits [ 0 ][ "color" ]  =  "red" 
	}

	if fruits [ 1 ] == nil { 
		fruits [ 1 ]  =  make ( map [ string ] string ,  2 ) 
		fruits [ 1 ] [ "name" ]  =  "banana" 
		fruits [ 1 ] [ "color" ]  =  "yellow" 
	}

	fruit :=  map [ string ] string { 
		"name"  :  "watermalon" , 
		"color"  :  "red and green" , 
	}

	fruits =  append ( fruits , fruit )

	fmt . Println ( fruits ) 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

Related: Basic use of map data type in Go language