8

Get slices of keys and values from a map

 3 years ago
source link: https://yourbasic.org/golang/slice-of-keys-values-from-map/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Get slices of keys and values from a map · YourBasic Go

Get slices of keys and values from a map

yourbasic.org/golang

You can use a range statement to extract slices of keys and values from a map.

keys := make([]keyType, 0, len(myMap))
values := make([]valueType, 0, len(myMap))

for k, v := range myMap {
	keys = append(keys, k)
	values = append(values, v)
}

Further reading

15-men-in-16-slots-thumb.jpg

Maps explained [code example]

Related

3 ways to find a key in a map
To check if a map contains a key, use the second return value. It's a boolean that indicates if the key exists.
yourbasic.org
Sort a map by key or value
To sort a map (which is an unordered collection) you must maintain a separate data structure, typically a slice of keys or values.
yourbasic.org

Follow on Twitter

Most Read

See all 178 Go articles

This work is licensed under a CC BY 3.0 license.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK