golang take one element from map code example
Example: golang take one element from map
package main
import (
"fmt"
)
func GetElement(m map[int]string) (key int, value string, ok bool) {
for key, value = range m {
return key, value, true
}
return key, value, false
}
func PopElement(m map[int]string) (key int, value string, ok bool) {
for key, value = range m {
defer delete(m, key)
return key, value, true
}
return key, value, false
}
func main() {
m := map[int]string{
1: "one",
2: "two",
3: "three",
}
fmt.Println("Taking elements without popping")
for i := 0; i < 5; i++ {
k, v, ok := GetElement(m)
fmt.Println(k, v, ok, m)
}
fmt.Println("\nTaking elements with popping")
for {
k, v, ok := PopElement(m)
fmt.Println(k, v, ok, m)
if !ok {
break
}
}
}