Iterating Over a Set
Part of the Logic & Flow section of Coddy's GO journey — lesson 36 of 68.
Now that you can add, check, and remove elements from your set, it's time to learn how to iterate through all the elements. Since your Go set is built on a map, you can use the familiar for...range loop to access each element.
To iterate over a set, you use the same syntax as iterating over a map, but you only care about the keys:
for color := range colors {
fmt.Println(color)
}Notice that we're only using one variable in the range loop. Since we don't need the values (which are all empty structs), we can ignore them entirely. This will print each color in your set, one per line.
You can also use the two-variable form if you prefer to be explicit about ignoring the value:
for color, _ := range colors {
fmt.Println(color)
}Keep in mind that maps in Go don't guarantee any particular order when iterating, so your set elements may be printed in a different order each time you run the program. This is perfectly normal behavior for sets, as they're designed for membership testing rather than maintaining order.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyBuild a music playlist analyzer that processes song collections and displays detailed information about each playlist using the Go set idiom. This challenge demonstrates how to iterate over sets to examine and report on their contents.
You will receive two inputs:
- A string containing rock songs separated by commas (e.g.,
"Bohemian Rhapsody,Stairway to Heaven,Hotel California,Sweet Child O Mine") - A string containing pop songs separated by commas (e.g.,
"Shape of You,Blinding Lights,Watermelon Sugar,Levitating")
Your task is to:
- Create two sets using the Go idiom
map[string]struct{}to store rock songs and pop songs separately - Parse both input strings by splitting them on commas to get individual song titles
- Add each song to the appropriate set using the empty struct literal
{}as the value - Display the rock playlist analysis:
- Header:
"Rock Playlist Analysis:" - Count:
"Total rock songs: [count]" - Songs header:
"Songs in rock playlist:" - Each song on a separate line:
"♪ [song_title]"
- Header:
- Display the pop playlist analysis:
- Header:
"Pop Playlist Analysis:" - Count:
"Total pop songs: [count]" - Songs header:
"Songs in pop playlist:" - Each song on a separate line:
"♪ [song_title]"
- Header:
- Create a combined playlist by merging both sets into a new set
- Display the combined playlist analysis:
- Header:
"Combined Playlist Analysis:" - Count:
"Total unique songs: [count]" - Songs header:
"All songs in combined playlist:" - Each song on a separate line:
"♫ [song_title]"
- Header:
- Finally, display a summary:
"Playlist Summary:""Rock songs: [rock_count]""Pop songs: [pop_count]""Combined unique songs: [combined_count]"
Use the strings package to split the input strings on commas. To iterate over each set, use the for...range loop with a single variable to access only the keys (song titles). This challenge demonstrates how iterating over Go sets allows you to examine all elements in a collection, making it perfect for analysis and reporting tasks.
Cheat sheet
To iterate over a set in Go, use the for...range loop with a single variable to access only the keys:
for color := range colors {
fmt.Println(color)
}You can also use the two-variable form and explicitly ignore the value:
for color, _ := range colors {
fmt.Println(color)
}Note that maps in Go don't guarantee any particular order when iterating, so set elements may appear in different orders each time you run the program.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strings"
)
func main() {
// Read full lines using bufio.Scanner (handles song titles with spaces)
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
rockSongs := scanner.Text()
scanner.Scan()
popSongs := scanner.Text()
// Create sets using Go idiom map[string]struct{}
rockSet := make(map[string]struct{})
popSet := make(map[string]struct{})
// Parse input strings and populate sets
rockList := strings.Split(rockSongs, ",")
popList := strings.Split(popSongs, ",")
// TODO: Write your code below
// Add songs to their respective sets
// Display rock playlist analysis (sort songs for consistent output)
// Display pop playlist analysis (sort songs for consistent output)
// Create and display combined playlist analysis (sort songs for consistent output)
// Display playlist summary
// Remember: Convert map keys to slice, sort, then iterate for consistent order
_ = rockSet
_ = popSet
_ = rockList
_ = popList
_ = fmt.Sprintf
_ = sort.Strings
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors6Idiomatic Go: Sets
The Set Idiom in GoCreating a SetAdding to a SetChecking for MembershipRemoving from a SetIterating Over a SetRecap - Unique Usernames