To create custom formatted output functions using fmt
in Go, you can define your own types and implement the fmt.Stringer
interface.
Here's an example that demonstrates how to create a custom output function for a Person
struct:
package main
import "fmt"
type Person struct {
Name string
Age int
Salary float64
}
func (p Person) String() string {
return fmt.Sprintf("Name: %s\nAge: %d\nSalary: $%.2f", p.Name, p.Age, p.Salary)
}
func main() {
p := Person{
Name: "John Doe",
Age: 30,
Salary: 5000.0,
}
fmt.Println(p)
}
In this code, the Person
struct implements the String()
method of the fmt.Stringer
interface. This method returns a formatted string representation of the Person
struct.
The String()
method formats the output using fmt.Sprintf()
, which allows you to use placeholders (%s
, %d
, %f
) to insert values from the struct fields.
When you call fmt.Println(p)
, Go's default Println()
function is used, which internally calls the String()
method of the fmt.Stringer
interface to get the custom formatted output.