Removing from a Set
Part of the Logic & Flow section of Coddy's GO journey — lesson 35 of 68.
Sometimes you need to remove elements from your set, and Go makes this straightforward using the built-in delete() function. Since your set is actually a map underneath, removing an element works exactly like removing a key from a map.
To remove an element from your set, use the delete() function with your set and the element you want to remove:
delete(colors, "red")The delete() function takes two parameters: the map (your set) and the key you want to remove. If the element exists in the set, it gets removed. If the element doesn't exist, the function does nothing - no error is thrown.
This behavior is perfect for sets because you often want to ensure an element is not present, regardless of whether it was there initially. The operation is fast and efficient, maintaining the performance benefits of Go's underlying map implementation.
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 library book management system that removes books from different genre collections using the Go set idiom. This challenge demonstrates how to use the delete() function to remove elements from sets while tracking the removal process.
You will receive two inputs:
- A string containing books in the fiction collection separated by commas (e.g.,
"1984,Dune,Foundation,Neuromancer,Brave New World") - A string containing books to remove separated by commas (e.g.,
"Dune,Harry Potter,Foundation,Twilight,1984")
Your task is to:
- Create a set using the Go idiom
map[string]struct{}to store the fiction books - Parse the first input string by splitting it on commas to get individual book titles
- Add each book 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 books to remove
- For each book to remove, check if it exists in the set using the comma ok idiom
- Display the removal process for each book being processed:
- If the book exists in the collection:
"Removing: [book_title]" - If the book doesn't exist in the collection:
"Not found: [book_title]"
- If the book exists in the collection:
- Use the
delete()function to remove books that exist in the set - After processing all removal requests, display a summary:
"Initial collection size: [initial_count]""Removal requests: [requests_count]""Books successfully removed: [removed_count]""Books not found: [not_found_count]""Final collection size: [final_count]"
- Finally, list all remaining books in the collection:
- Header:
"Remaining books in fiction collection:" - Each book on a separate line:
"- [book_title]" - If no books remain:
"- Collection is empty"
- Header:
Use the strings package to split the input strings on commas. This challenge demonstrates how the delete() function safely removes elements from a Go set, with no errors thrown even when attempting to remove non-existent elements, making it perfect for cleanup operations.
Cheat sheet
To remove elements from a set in Go, use the built-in delete() function:
delete(colors, "red")The delete() function takes two parameters: the map (your set) and the key you want to remove. If the element exists, it gets removed. If it doesn't exist, the function does nothing - no error is thrown.
This makes delete() perfect for sets since you often want to ensure an element is not present, regardless of whether it was there initially.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strings"
)
func main() {
// Read input using Scanner to support book titles with spaces
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
fictionBooks := scanner.Text()
scanner.Scan()
booksToRemove := scanner.Text()
// Parse input strings
fictionList := strings.Split(fictionBooks, ",")
removeList := strings.Split(booksToRemove, ",")
// TODO: Write your code below
// 1. Create a set using map[string]struct{} to store fiction books
// 2. Add each book from fictionList to the set
// 3. Process each book in removeList and check if it exists
// 4. Display removal process and use delete() function
// 5. Display summary statistics
// 6. List remaining books in the collection
// Remember to sort remaining books for consistent output
_ = sort.Strings // remove this line once you use sort
_ = fmt.Println // remove this line once you use fmt
}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