{"id":327,"date":"2019-10-20T08:32:13","date_gmt":"2019-10-20T08:32:13","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=327"},"modified":"2019-11-12T19:22:55","modified_gmt":"2019-11-12T19:22:55","slug":"different-ways-iterating-over-map-go","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/different-ways-iterating-over-map-go\/","title":{"rendered":"Different ways of iterating over a map in Go (Golang)"},"content":{"rendered":"\n
Range operator can be used to iterate over a map in Go<\/p>\n\n\n\n
Let’s define a map first<\/p>\n\n\n\n
sample := map[string]string{\n \"a\": \"x\",\n \"b\": \"y\",\n}<\/code><\/pre>\n\n\n\n- Iterating over all keys and values<\/strong><\/li><\/ul>\n\n\n\n
for k, v := range sample {\n fmt.Printf(\"key :%s value: %s\\n\", k, v)\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\nkey :a value: x\nkey :b value: y<\/code><\/pre>\n\n\n\n- Iterating over only keys<\/strong><\/li><\/ul>\n\n\n\n
for k := range sample {\n fmt.Printf(\"key :%s\\n\", k)\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\nkey :a\nkey :b<\/code><\/pre>\n\n\n\n- Iterating over only values<\/strong><\/li><\/ul>\n\n\n\n
for _, v := range sample {\n fmt.Printf(\"value :%s\\n\", v)\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\nvalue :x\nvalue :y<\/code><\/pre>\n\n\n\n- Get list of all keys<\/strong><\/li><\/ul>\n\n\n\n
keys := getAllKeys(sample)\nfmt.Println(keys)\n\nfunc getAllKeys(sample map[string]string) []string {\n var keys []string\n for k := range sample {\n keys = append(keys, k)\n }\n return keys\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\n[a b]<\/code><\/pre>\n\n\n\n
<\/p>\n","protected":false},"excerpt":{"rendered":"
Range operator can be used to iterate over a map in Go Let’s define a map first Iterating over all keys and values Output: Iterating over only keys Output: Iterating over only…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[3,4,48],"class_list":["post-327","post","type-post","status-publish","format-standard","hentry","category-tech","tag-go","tag-golang","tag-iteration"],"yoast_head":"\n
Different ways of iterating over a map in Go (Golang) - Welcome To Golang By Example<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n