🧰 Go’s Utility Toolbox: Your Swiss Army Knife
Imagine you have a magical toolbox. Every time you need to fix something, build something, or figure something out—there’s a perfect tool waiting inside. That’s what Go’s Standard Library utility packages are!
🎯 What’s Inside This Toolbox?
Think of Go’s utility packages like a superhero’s gadget belt:
| Tool | What It Does | Real-Life Analogy |
|---|---|---|
regexp |
Find patterns in text | Detective with a magnifying glass |
sort |
Organize things | Librarian arranging books |
flag |
Read commands | Waiter taking your order |
os/exec |
Run other programs | Boss delegating tasks |
reflect |
Look inside things | X-ray vision |
🔍 Regular Expression Operations (regexp)
The Pattern Detective
Imagine you’re a detective looking for clues in a giant book. Instead of reading every single word, you use a special magnifying glass that highlights exactly what you’re looking for.
That’s regexp! It finds patterns in text.
Your First Pattern Search
package main
import (
"fmt"
"regexp"
)
func main() {
// Our detective's magnifying glass
pattern := regexp.MustCompile(`\d+`)
text := "I have 3 cats and 2 dogs"
// Find all numbers!
numbers := pattern.FindAllString(text, -1)
fmt.Println(numbers) // [3 2]
}
Pattern Cheat Codes
graph TD A["Pattern Symbols"] --> B["\\d = any digit"] A --> C["\\w = any letter"] A --> D[". = any character"] A --> E["+ = one or more"] A --> F["* = zero or more"]
Common Pattern Operations
1. Check if pattern exists:
matched, _ := regexp.MatchString(
`^hello`, "hello world")
fmt.Println(matched) // true
2. Find first match:
re := regexp.MustCompile(`\w+@\w+\.\w+`)
email := re.FindString("Contact: a@b.com")
fmt.Println(email) // a@b.com
3. Replace patterns:
re := regexp.MustCompile(`cat`)
result := re.ReplaceAllString(
"I love my cat", "dog")
fmt.Println(result) // I love my dog
4. Split by pattern:
re := regexp.MustCompile(`[,;]+`)
parts := re.Split("a,b;c,,d", -1)
fmt.Println(parts) // [a b c d]
💡 Pro Tip: Use
MustCompilewhen you’re sure the pattern is valid. It panics on bad patterns—like a smoke alarm that screams when something’s wrong!
📚 Sorting Operations (sort)
The Librarian’s Magic
Picture a messy pile of books. A librarian waves their wand, and poof—everything is perfectly arranged! That’s the sort package.
Sorting Basics
package main
import (
"fmt"
"sort"
)
func main() {
// Messy numbers
nums := []int{5, 2, 8, 1, 9}
sort.Ints(nums)
fmt.Println(nums) // [1 2 5 8 9]
// Messy words
words := []string{"banana", "apple", "cherry"}
sort.Strings(words)
fmt.Println(words) // [apple banana cherry]
}
Sorting Your Way (Custom Sorting)
What if you want to sort differently? Like arranging books by size instead of title?
type Person struct {
Name string
Age int
}
func main() {
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
// Sort by age (youngest first)
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
// Bob(25), Alice(30), Charlie(35)
}
Reverse Sorting
nums := []int{1, 2, 3, 4, 5}
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
fmt.Println(nums) // [5 4 3 2 1]
Check if Already Sorted
nums := []int{1, 2, 3}
fmt.Println(sort.IntsAreSorted(nums)) // true
Binary Search (Super Fast Finding!)
nums := []int{1, 3, 5, 7, 9}
idx := sort.SearchInts(nums, 5)
fmt.Println(idx) // 2 (position of 5)
graph TD A["Sorting Methods"] --> B["sort.Ints"] A --> C["sort.Strings"] A --> D["sort.Float64s"] A --> E["sort.Slice - Custom!"] E --> F["You decide the rules!"]
🎛️ Command-Line Flag Parsing (flag)
The Waiter Taking Orders
When you go to a restaurant, the waiter asks: “How would you like your steak? Medium? Well done?”
The flag package is like that waiter—it asks users how they want the program to run!
Basic Flag Usage
package main
import (
"flag"
"fmt"
)
func main() {
// Define what we're asking
name := flag.String("name", "World",
"Your name")
age := flag.Int("age", 0,
"Your age")
verbose := flag.Bool("verbose", false,
"Show details")
// Listen for answers
flag.Parse()
// Use the answers
fmt.Printf("Hello, %s!\n", *name)
if *verbose {
fmt.Printf("You are %d years old\n", *age)
}
}
Running the program:
go run main.go -name=Alice -age=25 -verbose
Different Flag Types
| Type | Function | Example |
|---|---|---|
| String | flag.String |
-name=Alice |
| Integer | flag.Int |
-count=5 |
| Boolean | flag.Bool |
-verbose |
| Float | flag.Float64 |
-rate=3.14 |
| Duration | flag.Duration |
-timeout=5s |
Getting Extra Arguments
flag.Parse()
// Arguments after flags
extras := flag.Args()
fmt.Println(extras)
// go run main.go -v file1.txt file2.txt
// extras = [file1.txt file2.txt]
Flags Without Pointers
var name string
flag.StringVar(&name, "name", "World",
"Your name")
flag.Parse()
fmt.Println(name) // No * needed!
🤖 External Command Execution (os/exec)
The Boss Who Delegates
Imagine you’re a boss. Sometimes you need someone else to do a task. You tell them what to do, wait for them to finish, and get the result back.
That’s os/exec—Go asking OTHER programs to help!
Run a Simple Command
package main
import (
"fmt"
"os/exec"
)
func main() {
// Ask "ls" to list files
cmd := exec.Command("ls", "-la")
// Get the output
output, err := cmd.Output()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(output))
}
Send Input, Get Output
cmd := exec.Command("cat")
// Send input
cmd.Stdin = strings.NewReader("Hello!")
// Capture output
var out bytes.Buffer
cmd.Stdout = &out
cmd.Run()
fmt.Println(out.String()) // Hello!
Capture Errors Too
cmd := exec.Command("ls", "nonexistent")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println("Error:", stderr.String())
}
Combined Output (Stdout + Stderr)
cmd := exec.Command("ls", "-la")
output, err := cmd.CombinedOutput()
fmt.Println(string(output))
Check if Command Exists
path, err := exec.LookPath("python")
if err != nil {
fmt.Println("Python not found!")
} else {
fmt.Println("Python is at:", path)
}
graph TD A["Your Go Program"] -->|exec.Command| B["External Program"] B -->|Stdout| C["Results"] B -->|Stderr| D["Errors"] A -->|Stdin| B
🔮 Reflection Operations (reflect)
X-Ray Vision for Code
Remember Superman’s X-ray vision? He could see inside walls and boxes. The reflect package gives your code that power—it can look inside ANY variable and see what it really is!
See the Type of Anything
package main
import (
"fmt"
"reflect"
)
func main() {
x := 42
s := "hello"
fmt.Println(reflect.TypeOf(x)) // int
fmt.Println(reflect.TypeOf(s)) // string
}
See the Value
x := 3.14
v := reflect.ValueOf(x)
fmt.Println(v.Float()) // 3.14
fmt.Println(v.Kind()) // float64
Inspect a Struct
type Person struct {
Name string
Age int
}
func main() {
p := Person{"Alice", 30}
t := reflect.TypeOf(p)
// See all fields
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Printf("%s: %s\n",
field.Name, field.Type)
}
// Name: string
// Age: int
}
Change Values with Reflection
x := 10
v := reflect.ValueOf(&x).Elem()
if v.CanSet() {
v.SetInt(20)
}
fmt.Println(x) // 20
⚠️ Warning: You can only change values if you pass a pointer!
The Kind vs Type Difference
type MyInt int
var x MyInt = 5
t := reflect.TypeOf(x)
fmt.Println(t.Name()) // MyInt (specific type)
fmt.Println(t.Kind()) // int (underlying kind)
When to Use Reflection
graph TD A["Should I use reflect?"] --> B{Need to handle unknown types?} B -->|Yes| C{Is there another way?} B -->|No| D["Don&#39;t use reflect] C -->|Yes| E[Use that instead!] C -->|No| F[Use reflect carefully] F --> G[It&#39;s slower than normal code"]
🎁 Putting It All Together
Here’s a mini-program using ALL five utility packages:
package main
import (
"flag"
"fmt"
"os/exec"
"reflect"
"regexp"
"sort"
)
func main() {
// FLAG: Get user input
search := flag.String("find", "",
"Pattern to find")
flag.Parse()
// EXEC: Run a command
cmd := exec.Command("echo",
"3 cats, 1 dog, 2 birds")
output, _ := cmd.Output()
text := string(output)
// REGEXP: Find numbers
re := regexp.MustCompile(`\d+`)
nums := re.FindAllString(text, -1)
// SORT: Order them
sort.Strings(nums)
fmt.Println("Sorted:", nums)
// REFLECT: Show types
fmt.Println("Type:",
reflect.TypeOf(nums))
}
🌟 Key Takeaways
| Package | Remember This |
|---|---|
regexp |
🔍 Pattern detective |
sort |
📚 Magic librarian |
flag |
🎛️ Friendly waiter |
os/exec |
🤖 Delegating boss |
reflect |
🔮 X-ray vision |
🚀 You Did It!
You now have a complete utility toolbox in Go! These five packages handle:
✅ Finding patterns in text ✅ Organizing data perfectly ✅ Taking user commands ✅ Running external programs ✅ Inspecting anything at runtime
Go build something amazing! 🎉
