Custom Output Strategies
Advanced Output Techniques in Go
Custom output strategies allow developers to create more flexible and sophisticated ways of presenting data and handling complex formatting scenarios.
type User struct {
Name string
Email string
Active bool
}
func (u User) String() string {
status := "Inactive"
if u.Active {
status = "Active"
}
return fmt.Sprintf("User: %s <%s> [%s]", u.Name, u.Email, status)
}
Output Strategy Workflow
graph TD
A[Custom Output] --> B{Define Interface}
B --> C[Implement Methods]
C --> D[Create Custom Formatter]
D --> E[Use in Application]
Strategy |
Use Case |
Complexity |
Performance |
fmt.Stringer |
Simple object representation |
Low |
High |
Custom Formatter |
Complex formatting |
Medium |
Medium |
Template Rendering |
Dynamic content |
High |
Low |
type JSONFormatter struct {
data interface{}
}
func (jf *JSONFormatter) Format() (string, error) {
output, err := json.MarshalIndent(jf.data, "", " ")
if err != nil {
return "", err
}
return string(output), nil
}
Error Handling Strategies
type DetailedError struct {
Message string
Code int
Context map[string]interface{}
}
func (e *DetailedError) Error() string {
return fmt.Sprintf("Error %d: %s (Context: %v)",
e.Code, e.Message, e.Context)
}
Writer Interface Customization
type LogWriter struct {
prefix string
}
func (lw *LogWriter) Write(p []byte) (n int, err error) {
formattedLog := fmt.Sprintf("%s: %s", lw.prefix, string(p))
return os.Stdout.Write([]byte(formattedLog))
}
LabEx Recommendation
When developing custom output strategies, LabEx suggests focusing on:
- Clarity of implementation
- Performance considerations
- Consistent error handling
Best Practices
- Implement
fmt.Stringer
for custom types
- Use interfaces for flexibility
- Handle potential formatting errors
- Keep output strategies modular and reusable