Algorithm
Code Examples
#1 Map in Golang Programming
Code -
Golang Programming
// Program to create a map and print its keys and values
package main
import "fmt"
func main() {
// create a map
subjectMarks := map[string]float32{"Golang": 85, "Java": 80, "Python": 81}
fmt.Println(subjectMarks)
}
Copy The Code &
Try With Live Editor
Output
#2 Access Values of a Map in Golang Programming
Code -
Golang Programming
package main
import "fmt"
func main() {
// create a map
flowerColor := map[string]string{"Sunflower": "Yellow", "Jasmine": "White", "Hibiscus": "Red"}
// access value for key Sunflower
fmt.Println(flowerColor["Sunflower"]) // Yellow
// access value for key Hibiscus
fmt.Println(flowerColor["Hibiscus"]) // Red
}
Copy The Code &
Try With Live Editor
#3 Change value of a map in Golang Programming
Code -
Golang Programming
package main
import "fmt"
func main() {
// create a map
capital := map[string]string{ "Nepal": "Kathmandu", "US": "New York"}
fmt.Println("Initial Map: ", capital)
// change value of US to Washington DC
capital["US"] = "Washington DC"
fmt.Println("Updated Map: ", capital)
}
Copy The Code &
Try With Live Editor
Output
Updated Map: map[Nepal: Kathmandu US: Washington DC]
#4 Add Element of Golang Map Element
Code -
Golang Programming
package main
import "fmt"
func main() {
// create a map
students := map[int]string{1: "John", 2: "Lily"}
fmt.Println("Initial Map: ", students)
// add element with key 3
students[3] = "Robin"
// add element with key 5
students[5] = "Julie"
fmt.Println("Updated Map: ", students)
}
Copy The Code &
Try With Live Editor
Output
Updated Map: map[1:John 2:Lily 3:Robin 5:Julie]
#5 Delete Element of Golang Map Element
Code -
Golang Programming
package main
import "fmt"
func main() {
// create a map
personAge := map[string]int{"Hermione": 21, "Harry": 20, "John": 25}
fmt.Println("Initial Map: ", personAge)
// remove element of map with key John
delete(personAge, "John")
fmt.Println("Updated Map: ", personAge)
}
Copy The Code &
Try With Live Editor
Output
Updated Map: map[Harry:20 Hermione:21]
#6 Looping through the map in Golang Programming
Code -
Golang Programming
package main
import "fmt"
func main() {
// create a map
squaredNumber := map[int]int{2: 4, 3: 9, 4: 16, 5: 25}
// for-range loop to iterate through each key-value of map
for number, squared := range squaredNumber {
fmt.Printf("Square of %d is %d\n", number, squared)
}
}
Copy The Code &
Try With Live Editor
Output
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
Demonstration
Go Lang Programming map