Go Standard Library
Exploring Go's built-in packages and functions
📚 What is Go Standard Library?
Go's standard library is a collection of built-in packages that provide essential functionality for common programming tasks like I/O, networking, text processing, and more without external dependencies.
package main
import (
"fmt" // Formatted I/O
"time" // Time and date
"strings" // String utilities
)
func main() {
fmt.Println("Current time:", time.Now().Format("2006-01-02"))
fmt.Println("Uppercase:", strings.ToUpper("hello world"))
}
Output:
Current time: 2024-01-15
Uppercase: HELLO WORLD
Standard Library Categories
I/O & Formatting
Input/output and text formatting
import (
"fmt"
"io"
"bufio"
)
String & Text
String manipulation and processing
import (
"strings"
"strconv"
"regexp"
)
Network & HTTP
Networking and web functionality
import (
"net/http"
"net/url"
"encoding/json"
)
Time & Math
Time handling and mathematical operations
import (
"time"
"math"
"math/rand"
)
🔹 Essential I/O Packages
Most commonly used packages for input and output:
🔸 fmt Package - Formatted I/O:
package main
import "fmt"
func main() {
name := "Alice"
age := 30
// Print functions
fmt.Print("Hello ")
fmt.Println("World!")
// Formatted printing
fmt.Printf("Name: %s, Age: %d\n", name, age)
// Sprint functions (return strings)
message := fmt.Sprintf("User: %s (%d years old)", name, age)
fmt.Println(message)
}
Output:
Hello World!
Name: Alice, Age: 30
User: Alice (30 years old)
🔹 String Manipulation
Working with strings using the strings package:
package main
import (
"fmt"
"strings"
"strconv"
)
func main() {
text := " Hello, Go World! "
// String operations
fmt.Println("Original:", text)
fmt.Println("Trimmed:", strings.TrimSpace(text))
fmt.Println("Uppercase:", strings.ToUpper(text))
fmt.Println("Lowercase:", strings.ToLower(text))
fmt.Println("Contains 'Go':", strings.Contains(text, "Go"))
fmt.Println("Replace:", strings.Replace(text, "World", "Universe", 1))
// String conversion
number := 42
str := strconv.Itoa(number)
fmt.Println("Number to string:", str)
back, _ := strconv.Atoi(str)
fmt.Println("String to number:", back)
}
Output:
Original: Hello, Go World!
Trimmed: Hello, Go World!
Uppercase: HELLO, GO WORLD!
Lowercase: hello, go world!
Contains 'Go': true
Replace: Hello, Go Universe!
Number to string: 42
String to number: 42
🔹 Time and Date
Working with time using the time package:
package main
import (
"fmt"
"time"
)
func main() {
// Current time
now := time.Now()
fmt.Println("Current time:", now)
// Formatted time
fmt.Println("Formatted:", now.Format("2006-01-02 15:04:05"))
fmt.Println("Date only:", now.Format("January 2, 2006"))
fmt.Println("Time only:", now.Format("3:04 PM"))
// Time calculations
tomorrow := now.Add(24 * time.Hour)
fmt.Println("Tomorrow:", tomorrow.Format("2006-01-02"))
// Duration
duration := time.Since(now)
fmt.Println("Duration since now:", duration)
}
Output:
Current time: 2024-01-15 14:30:25.123456789 +0000 UTC
Formatted: 2024-01-15 14:30:25
Date only: January 15, 2024
Time only: 2:30 PM
Tomorrow: 2024-01-16
Duration since now: 0s
🔹 Math Operations
Mathematical functions using the math package:
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
// Basic math operations
fmt.Println("Square root of 16:", math.Sqrt(16))
fmt.Println("Power 2^3:", math.Pow(2, 3))
fmt.Println("Absolute value of -5:", math.Abs(-5))
fmt.Println("Ceiling of 4.2:", math.Ceil(4.2))
fmt.Println("Floor of 4.8:", math.Floor(4.8))
// Constants
fmt.Println("Pi:", math.Pi)
fmt.Println("E:", math.E)
// Random numbers
rand.Seed(time.Now().UnixNano())
fmt.Println("Random int (0-99):", rand.Intn(100))
fmt.Println("Random float:", rand.Float64())
}
Output:
Square root of 16: 4
Power 2^3: 8
Absolute value of -5: 5
Ceiling of 4.2: 5
Floor of 4.8: 4
Pi: 3.141592653589793
E: 2.718281828459045
Random int (0-99): 73
Random float: 0.6046602879796196
🔹 JSON Handling
Working with JSON data using encoding/json:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
City string `json:"city"`
}
func main() {
// Create a person
person := Person{
Name: "John Doe",
Age: 30,
City: "New York",
}
// Convert to JSON
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("JSON:", string(jsonData))
// Parse JSON
jsonString := `{"name":"Jane Smith","age":25,"city":"London"}`
var newPerson Person
err = json.Unmarshal([]byte(jsonString), &newPerson)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Parsed: %+v\n", newPerson)
}
Output:
JSON: {"name":"John Doe","age":30,"city":"New York"}
Parsed: {Name:Jane Smith Age:25 City:London}
🔹 Common Standard Library Packages
Quick reference of essential standard library packages:
Essential Packages:
- fmt - Formatted I/O (print, scan, format)
- strings - String manipulation functions
- strconv - String conversions
- time - Time and date operations
- math - Mathematical functions
- math/rand - Random number generation
- encoding/json - JSON encoding/decoding
- net/http - HTTP client and server
- io - I/O primitives
- os - Operating system interface