Creating a Set
Part of the Logic & Flow section of Coddy's GO journey — lesson 32 of 68.
Now that you understand the concept behind Go's set idiom, it's time to put it into practice by creating your first set. The process is straightforward and follows the same patterns you've already learned with maps.
To create a set in Go, you declare a variable using the map[T]struct{} pattern, where T is the type of elements you want to store. Here's how you create a set to store unique color names:
colors := make(map[string]struct{})You can also initialize a set with some starting values using the map literal syntax:
colors := map[string]struct{}{
"red": {},
"blue": {},
"green": {},
}Notice how each value is an empty struct literal {}. This creates the zero value of struct{}, which takes up no memory space while still allowing the key to exist in the map.
The beauty of this approach is that it leverages Go's existing map infrastructure while providing true set semantics - each color name can only appear once, and you get fast lookup times just like with regular maps.
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
EasyCreate a programming language preference tracker that demonstrates the Go set idiom for storing unique items. This challenge shows how to use the map[string]struct{} pattern to track programming languages without duplicates.
You will receive two inputs:
- A string representing the number of languages to process (e.g.,
"6") - A string containing programming languages separated by commas (e.g.,
"Go,Python,JavaScript,Go,Java,Python,C++,JavaScript")
Your task is to:
- Create a set using the Go idiom
map[string]struct{}to store unique programming languages - Parse the input string by splitting it on commas to get individual language names
- Add each language to your set using the empty struct literal
{}as the value - Display the processing results by printing each language as it's encountered:
- If the language is new to the set:
"Added: [language]" - If the language already exists in the set:
"Already exists: [language]"
- If the language is new to the set:
- After processing all languages, display a summary:
"Total languages processed: [total_count]""Unique languages: [unique_count]"
- Finally, list all unique languages in the set:
- Header:
"Programming languages in set:" - Each language on a separate line:
"- [language]"
- Header:
Use the strings package to split the input string and the strconv package to convert the count string to an integer. To check if a language already exists in the set before adding it, use the comma ok idiom: _, exists := languageSet[language]. This challenge demonstrates how the Go set idiom provides an efficient way to track unique items and prevent duplicates in your data.
Cheat sheet
To create a set in Go, use the map[T]struct{} pattern where T is the element type:
colors := make(map[string]struct{})You can also initialize a set with starting values using map literal syntax:
colors := map[string]struct{}{
"red": {},
"blue": {},
"green": {},
}Each value is an empty struct literal {} which creates the zero value of struct{} and takes up no memory space while allowing the key to exist in the map.
To check if an element exists in the set, use the comma ok idiom:
_, exists := languageSet[language]Try it yourself
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func main() {
// Read input
var countStr string
var languagesStr string
fmt.Scanln(&countStr)
fmt.Scanln(&languagesStr)
// Convert count string to integer (not needed for this challenge)
_, _ = strconv.Atoi(countStr)
// Split the languages string by commas
languages := strings.Split(languagesStr, ",")
// Create a set using map[string]struct{} idiom
languageSet := make(map[string]struct{})
// TODO: Write your code below
// Process each language and check if it exists in the set
// Use comma ok idiom: _, exists := languageSet[language]
// Print "Added: [language]" or "Already exists: [language]"
// Add languages to the set using empty struct literal {}
// Print summary information
// Print total languages processed and unique languages count
// Print all unique languages in the set
fmt.Println("Programming languages in set:")
// Convert map to slice and sort for consistent output
// List each language with "- [language]" format
}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