PROGRAM:
package main
import (
"fmt"
)
func main() {
/* Declare a map with key type as integer and value type as string */
var m map[int]string
/*
* Map type is a reference type, default value is nil writing to empty
* gives runtime panic. Initialize map type with the help of make statement
*/
m = make(map[int]string)
/* Write data to map */
m[1] = "John"
m[2] = "Peter"
m[3] = "James"
m[4] = "Steve"
m[5] = "Bill"
/* Read from map */
v, ok := m[3]
fmt.Println("Avail:", ok, " Name:", v)
/* Delete from map */
delete(m, 5)
v, ok = m[5]
fmt.Println("Avail:", ok, " Name:", v)
/* Get Number of items in map */
count := len(m)
fmt.Println("Number of items:", count)
/* Iterate over map using range */
for key, value := range m {
fmt.Println(key, "- ", value)
}
}
OUTPUT:
Avail: true Name: James
Avail: false Name:
Number of items: 4
1 - John
2 - Peter
3 - James
4 - Steve
package main
import (
"fmt"
)
func main() {
/* Declare a map with key type as integer and value type as string */
var m map[int]string
/*
* Map type is a reference type, default value is nil writing to empty
* gives runtime panic. Initialize map type with the help of make statement
*/
m = make(map[int]string)
/* Write data to map */
m[1] = "John"
m[2] = "Peter"
m[3] = "James"
m[4] = "Steve"
m[5] = "Bill"
/* Read from map */
v, ok := m[3]
fmt.Println("Avail:", ok, " Name:", v)
/* Delete from map */
delete(m, 5)
v, ok = m[5]
fmt.Println("Avail:", ok, " Name:", v)
/* Get Number of items in map */
count := len(m)
fmt.Println("Number of items:", count)
/* Iterate over map using range */
for key, value := range m {
fmt.Println(key, "- ", value)
}
}
OUTPUT:
Avail: true Name: James
Avail: false Name:
Number of items: 4
1 - John
2 - Peter
3 - James
4 - Steve
No comments:
Post a Comment