Thursday 2 May 2019

Go Language: Map data structure


‘map’ is a data structure used to store key-value pairs.

Syntax
mapName := make(map[keyDataType]valueDataType)

Example
employees := make(map[int]string)

HelloWorld.go
package main

import "fmt"

func main() {
 employees := make(map[int]string)

 fmt.Println("Empty Map : ", employees)

 employees[1] = "Krishna"
 employees[12] = "Sibi"

 fmt.Println("Map with two elements : ", employees)
}

Output
Empty Map :  map[]
Map with two elements :  map[1:Krishna 12:Sibi]


You can access an entry in the map using the key.

For example, ‘employees[12]’ access the entry in map with key 12.


HelloWorld.go

package main

import "fmt"

func main() {
 employees := make(map[int]string)

 fmt.Println("Empty Map : ", employees)

 employees[1] = "Krishna"
 employees[12] = "Sibi"

 fmt.Println("Value of key 12 is ", employees[12])
 fmt.Println("Value of key 123 is ", employees[123])
}

Output
Empty Map :  map[]
Value of key 12 is  Sibi
Value of key 123 is 


Since there is no entry with key 123, employees[123] returns an empty string.


Previous                                                 Next                                                 Home

No comments:

Post a Comment