How to implement custom formatting for user-defined types in Go?

In Go, you can implement custom formatting for user-defined types by implementing the fmt.Stringer interface.

The fmt.Stringer interface specifies a single method called String() that returns a string representation of the object. By implementing this method for your type, you can control how the object is formatted when passed to functions like fmt.Print() or used in string interpolation.

Here's an example:

package main import "fmt" type Person struct { Name string Age int Height float64 } // Implement the Stringer interface for Person func (p Person) String() string { return fmt.Sprintf("Name: %s, Age: %d, Height: %.2f", p.Name, p.Age, p.Height) } func main() { person := Person{Name: "John", Age: 30, Height: 175.5} fmt.Println(person) // This will print "Name: John, Age: 30, Height: 175.5" }

In the above example, the Person struct implements the String() method that formats the object's fields using fmt.Sprintf(). When fmt.Print() or any other function that requires a string representation is called on the Person object, the String() method is automatically called, and the returned string is used for formatting.