Checking for Membership
Part of the Logic & Flow section of Coddy's GO journey — lesson 34 of 68.
Now that you can add elements to your set, the next essential operation is checking whether a specific element exists in the set. This is where Go's "comma ok" idiom becomes incredibly useful.
To check if an element exists in your set, you use the same syntax as checking for a key in a map:
_, ok := colors["red"]
if ok {
fmt.Println("Red is in the set")
} else {
fmt.Println("Red is not in the set")
}The underscore _ is used because we don't care about the actual value (which is always an empty struct). We only care about the boolean ok variable, which tells us whether the key exists.
You can also use this pattern directly in an if statement for more concise code:
if _, exists := colors["blue"]; exists {
fmt.Println("Blue is in the set")
}This membership testing is fast and efficient, leveraging Go's optimized map implementation to give you the performance benefits of a true set data structure.
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 team member verification system that checks if specific people are part of a project team using the Go set idiom. This challenge demonstrates how to use the comma ok idiom to test for membership in a set.
You will receive two inputs:
- A string containing team members separated by commas (e.g.,
"Alice,Bob,Charlie,Diana,Eve") - A string containing people to check separated by commas (e.g.,
"Bob,Frank,Alice,Grace,Charlie")
Your task is to:
- Create a set using the Go idiom
map[string]struct{}to store the team members - Parse the first input string by splitting it on commas to get individual team member names
- Add each team member to your set using the empty struct literal
{}as the value - Parse the second input string by splitting it on commas to get the list of people to verify
- For each person to check, use the comma ok idiom
_, ok := teamSet[person]to test membership - Display the verification results for each person being checked:
- If the person is in the team:
"[person] is on the team" - If the person is not in the team:
"[person] is not on the team"
- If the person is in the team:
- After checking all people, display a summary:
"Team size: [team_member_count]""People checked: [people_checked_count]""Team members found: [found_count]""Non-team members: [not_found_count]"
Use the strings package to split the input strings on commas. This challenge demonstrates how the comma ok idiom provides a safe and efficient way to check for membership in a Go set, returning both the value and a boolean indicating whether the key exists.
Cheat sheet
To check if an element exists in a set (map), use the "comma ok" idiom:
_, ok := colors["red"]
if ok {
fmt.Println("Red is in the set")
} else {
fmt.Println("Red is not in the set")
}The underscore _ discards the value since we only care about the boolean ok variable that indicates if the key exists.
You can also use this pattern directly in an if statement:
if _, exists := colors["blue"]; exists {
fmt.Println("Blue is in the set")
}Try it yourself
package main
import (
"fmt"
"strings"
)
func main() {
// Read input
var teamMembersInput string
var peopleToCheckInput string
fmt.Scanln(&teamMembersInput)
fmt.Scanln(&peopleToCheckInput)
// Parse input strings
teamMembers := strings.Split(teamMembersInput, ",")
peopleToCheck := strings.Split(peopleToCheckInput, ",")
// TODO: Write your code below
// Create a set using map[string]struct{}
// Add team members to the set
// Check each person using the comma ok idiom
// Display verification results and summary
}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