type Person struct { Name string Age int Address string } func (p Person) String() string { return fmt.Sprintf("%v (%v years old), Address: %v", p.Name, p.Age, p.Address) } func main() { person := Person{Name: "John Smith", Age: 35, Address: "123 Main St"} fmt.Println(person) }
type Rectangle struct { Width int Height int } func (r Rectangle) String() string { return fmt.Sprintf("Rectangle{Width: %v, Height: %v}", r.Width, r.Height) } func main() { rect := Rectangle{Width: 10, Height: 20} fmt.Println(rect) }In this example, we define a Rectangle struct with Width and Height fields. We then implement the String() method to generate a custom string representation using the fmt.Sprintf function. When we call fmt.Println(rect), the custom string representation is printed. The package library for fmt.Stringer is "fmt".