Printf offers sophisticated formatting capabilities that go beyond basic string output. Understanding these techniques can significantly enhance your string manipulation skills in Go.
Width and Precision Specifiers
graph TD
A[Printf Specifiers] --> B[Width Control]
A --> C[Precision Control]
B --> D[%5d: Minimum Width]
B --> E[%-5d: Left Alignment]
C --> F[%.2f: Decimal Precision]
Specifier |
Description |
Example |
%+d |
Show sign for numbers |
fmt.Printf("%+d", 42) |
%04d |
Zero-pad numbers |
fmt.Printf("%04d", 42) |
%x |
Hexadecimal representation |
fmt.Printf("%x", 255) |
%#v |
Go-syntax representation |
fmt.Printf("%#v", struct) |
package main
import "fmt"
type User struct {
Name string
Age int
}
func main() {
// Alignment and padding
fmt.Printf("Padded: %5d\n", 42)
// Struct formatting
user := User{"LabEx", 25}
fmt.Printf("User Details: %+v\n", user)
// Multiple format specifiers
fmt.Printf("Name: %s, Age: %d, Hex: %x\n", "LabEx", 25, 25)
}
Escape Sequences
// Handling special characters
fmt.Printf("Newline: %s\n", "Hello\nWorld")
fmt.Printf("Tab: %s\n", "Hello\tWorld")
Dynamic Width and Precision
// Dynamic width and precision
name := "LabEx"
fmt.Printf("Dynamic: %*.*s\n", 10, 3, name)
- Use
Printf
judiciously
- For simple concatenations, prefer
strings.Builder
- Avoid excessive formatting in performance-critical code
Key Takeaways
- Printf offers granular control over string formatting
- Specifiers can modify width, alignment, and representation
- Understanding format techniques improves code readability
- Choose the right formatting method for your specific use case