Golang Accessing Elements from Map
In this tutorial, we will learn how to access specific element from a Map by using key of the map along with the working examples of it. As we know GO Map will store the key-value pair type of data.
Accessing Items
In the Go language, we can access the map values by using the map key.
Syntax:
map[key]
Access Map Example 1:
Let us create a map named manager with 2 key-value pairs and access them.
package main
import ("fmt")
func main() {
// Create an empty map such that key stores string type values,
//value stores integer type values and add 2 key-value pairs.
var manager = map[string]int{"Sravan":23,"Anil":35}
// Display the map
fmt.Println(manager)
// Access value of "Sravan"
fmt.Println("Sravan Age:",manager["Sravan"])
// Access value of "Sravan"
fmt.Println("Anil Age:",manager["Anil"])
}
Output:
map[Anil:35 Sravan:23]
Sravan Age: 23
Anil Age: 35
The values were returned based on the key. Suppose, if there is no key and if we try to return it, 0 is returned as value.
Access Map Example 2:
Let us create a map named manager with 2 key-value pairs and access unknown value.
package main
import ("fmt")
func main() {
// Create an empty map such that key stores string type values,
//value stores integer type values and add 2 key-value pairs.
var manager = map[string]int{"Sravan":23,"Anil":35}
// Display the map
fmt.Println(manager)
// Access value of "Ramya"
fmt.Println("Ramya Age:",manager["Ramya"])
}
Output:
map[Anil:35 Sravan:23]
Ramya Age: 0
Explanation for the above output:
The value is 0 because, Ramya not exists in the map.
Access Map Example 3:
Let us create a map named fruits with 5 key-value pairs and access them.
package main
import ("fmt")
func main() {
// Create an empty map such that key and value stores string type // values and add 5 key-value pairs.
var fruits = map[string]string{"apple":"guntur","guava":"nepal","banana":"guntur","grapes":"hyd","papayya":"hyd"}
// Display the map
fmt.Println(fruits)
// Access value of "apple"
fmt.Println("Apple Area:",fruits["apple"])
// Access value of "guava"
fmt.Println("Guava Area:",fruits["guava"])
}
Output:
map[apple:guntur guava:nepal banana:guntur grapes:hyd papayya:hyd]
Apple Area: guntur
Guava Area: nepal
Explanation for the above output:
The values were returned based on the key.
Conclusion:
Now we know how to return the values present in the Go Map using key and understood the implementation with working examples.