Alignment and Padding
func alignmentExamples() {
// Right-aligned with width
fmt.Printf("%10d\n", 42) // Spaces before number
fmt.Printf("%-10d\n", 42) // Left-aligned
fmt.Printf("%05d\n", 42) // Zero-padded
}
Specifier |
Purpose |
Example |
%+v |
Show struct field names |
Printf("%+v", struct) |
%#v |
Go-syntax representation |
Printf("%#v", value) |
%x |
Hexadecimal representation |
Printf("%x", 255) |
%b |
Binary representation |
Printf("%b", 42) |
Nested Structures
type User struct {
Name string
Age int
}
func complexFormatting() {
user := User{Name: "LabEx", Age: 25}
fmt.Printf("Detailed User: %+v\n", user)
fmt.Printf("Go-syntax User: %#v\n", user)
}
graph TD
A[Input Data] --> B{Determine Format}
B --> |Simple| C[Basic Printf]
B --> |Complex| D[Advanced Specifiers]
B --> |Custom| E[Custom Formatting]
func efficientFormatting() {
// Prefer buffer for multiple formatting
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("Value: %d", 42))
}
func errorHandling() {
err := fmt.Errorf("custom error: %s", "operation failed")
fmt.Printf("Error details: %v\n", err)
}
func dynamicFormatting(format string, values ...interface{}) {
fmt.Printf(format, values...)
}
// Usage example
dynamicFormatting("Name: %s, Age: %d\n", "Alice", 30)
Precision Control
func precisionControl() {
pi := 3.14159
fmt.Printf("Default: %f\n", pi) // Full precision
fmt.Printf("Two decimals: %.2f\n", pi) // Two decimal places
fmt.Printf("Padded: %8.2f\n", pi) // Width and precision
}
Best Practices
- Choose appropriate format specifiers
- Use width and precision modifiers
- Handle complex data structures
- Optimize for performance
- Implement clear error handling
Common Pitfalls to Avoid
- Mismatched format specifiers
- Ignoring type conversions
- Overlooking performance implications
- Neglecting error handling
LabEx Recommended Approach
When working with Printf in complex scenarios, always:
- Plan your formatting strategy
- Use type-specific conversions
- Test with various input types
- Monitor performance impact