Maps in Go

Maps are used to store key-value pairs.

mapName := map[keyDataType]valueDataType
//assign key value
mapName[key] = value

//declare and initialize at once
initMap := map[keyDataType]valueDataType{key: value}


Maps are dynamically sized.

These are equivalent to dictionaries, associative arrays, and HashMaps in other languages.

A pair can be deleted from a map using the 'delete(mapName, key)' function.

A second variable can be assigned to the result of fetching the key to check for presence of the key. Check the example below.

grades := map[string]int
grades["Paul"] = 85
grades["Alan"] = 75

fmt.Println("Paul's grade is: ", grades["Paul"])
//check for presence of student in map
if grade, present = grades["Anthony"]; present == true {
    fmt.Println("Anthony is present.") 
else {
    fmt.Println("Anthony is not present")

< Slices   |   Structs >

© 2018 SyntaxDB. All Rights Reserved.