Home
Go
Map With String Slices
Updated Apr 14, 2023
Dot Net Perls
Map, string slices. In Go programming we reuse common forms. We have string slices—these can contain many strings, and we can append strings as needed.
map
With a map, we can place string slices as the values. So we can associate string keys with lists of values. This is powerful. It helps in many Go programs.
Main example. Here we use a map of string slices in the main func. We initialize the map with two keys—each has its own string slice.
Then We append to the string slice at the key "dog." The word "dog" is not important—you can change it.
Next We add a new slice at the key "fish" with some more color words: "orange" and "red."
Finally We use a for-range loop over the slice at the key "fish." We print indexes and values for the string slice.
for
package main import "fmt" func main() { // Create map of string slices. m := map[string][]string { "cat": {"orange", "grey"}, "dog": {"black"}, } // Add a string at the dog key. // ... Append returns the new string slice. res := append(m["dog"], "brown") fmt.Println(res) // Add a key for fish. m["fish"] = []string{"orange", "red"} // Print slice at key. fmt.Println(m["fish"]) // Loop over string slice at key. for i := range m["fish"] { fmt.Println(i, m["fish"][i]) } }
[black brown] [orange red] 0 orange 1 red
With append, we can add elements to a string slice in a map. And with delete we can remove elements. Len will return the element count.
Slice
len
A summary. In Go, common things like a map that contains string slices are important to master. More complex things are nice, but often used less.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 14, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen