Practical Examples
Real-World Printf Applications
Printf is a versatile function with numerous practical applications across different programming scenarios in Golang.
1. Data Logging and Reporting
package main
import (
"fmt"
"time"
)
func logUserActivity(username string, loginTime time.Time) {
fmt.Printf("User: %-15s | Login Time: %s | Status: %s\n",
username,
loginTime.Format("2006-01-02 15:04:05"),
"Successful")
}
func main() {
logUserActivity("LabEx_Developer", time.Now())
}
func calculateSalary(name string, hours float64, rate float64) {
totalSalary := hours * rate
fmt.Printf("Employee: %s\n", name)
fmt.Printf("Hours Worked: %.2f\n", hours)
fmt.Printf("Hourly Rate: $%.2f\n", rate)
fmt.Printf("Total Salary: $%8.2f\n", totalSalary)
}
func main() {
calculateSalary("John Doe", 40.5, 25.50)
}
3. Debugging and Inspection
graph LR
A[Printf Debugging] --> B[Variable Inspection]
A --> C[Type Checking]
A --> D[Runtime Information]
B --> E[Print Values]
C --> F[Show Data Types]
D --> G[Timestamp Logging]
type Product struct {
Name string
Price float64
Quantity int
}
func displayInventory(products []Product) {
fmt.Printf("%-20s | %10s | %8s | %10s\n",
"Product Name", "Price", "Quantity", "Total Value")
fmt.Println(strings.Repeat("-", 55))
for _, p := range products {
totalValue := p.Price * float64(p.Quantity)
fmt.Printf("%-20s | $%9.2f | %8d | $%9.2f\n",
p.Name, p.Price, p.Quantity, totalValue)
}
}
func main() {
inventory := []Product{
{"Laptop", 1200.50, 5},
{"Smartphone", 599.99, 10},
}
displayInventory(inventory)
}
func validateInput(value int) error {
if value < 0 {
return fmt.Errorf("invalid input: value %d must be non-negative", value)
}
return nil
}
func main() {
err := validateInput(-5)
if err != nil {
fmt.Printf("Error: %v\n", err)
}
}
Scenario |
Printf Benefit |
Example Use Case |
Logging |
Precise formatting |
User activity tracking |
Reporting |
Aligned output |
Financial statements |
Debugging |
Type and value inspection |
Variable state analysis |
Data Presentation |
Consistent formatting |
Inventory display |
Best Practices
- Choose appropriate formatting specifiers
- Use width and precision controls
- Handle potential formatting errors
- Consider performance for large-scale printing
- Use Printf for structured, readable output
By mastering these practical examples, developers can leverage Printf for various complex formatting and reporting tasks in Golang applications.