How to implement custom formatting for structured data (e.g., structs, maps) in Go?

In Go, custom formatting for structured data can be implemented using the fmt package's Stringer interface and its String() method. Here's how you can go about it:

  1. Create a new type that represents your structured data. For example, if you want to implement custom formatting for a struct called Person, define the type Person:
type Person struct { Name string Age int }
  1. Implement the fmt.Stringer interface for the Person type. This interface requires implementing a String() method that returns a string representation of the data. Customize the String() method to format the Person type according to your desired output format. For example:
func (p Person) String() string { return fmt.Sprintf("Name: %s, Age: %d", p.Name, p.Age) }
  1. Use the custom String() method to format your structured data when printing or displaying it. For example:
p := Person{Name: "John Doe", Age: 25} fmt.Println(p) // Output: Name: John Doe, Age: 25

Now, whenever you need to print or display a Person object, the custom formatting defined in the String() method will be applied. You can extend this approach to other structured data types like maps by creating custom types for them and implementing the Stringer interface accordingly.