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:
struct
called Person
, define the type Person
:type Person struct {
Name string
Age int
}
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)
}
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.