To implement the Stringer
interface by embedding it in a custom struct in Go, follow these steps:
Define a custom struct that represents your data. Let's say we want to create a struct named Person
with name
and age
fields:
type Person struct {
name string
age int
}
Embed the fmt.Stringer
interface within your struct. This is done by adding a field of type fmt.Stringer
within the struct definition:
type Person struct {
name string
age int
}
func (p Person) String() string {
return fmt.Sprintf("Name: %s, Age: %d", p.name, p.age)
}
Implement the String()
method for the Person
struct. This method is defined on the struct and returns a string representation of the struct:
func (p Person) String() string {
return fmt.Sprintf("Name: %s, Age: %d", p.name, p.age)
}
Use the String()
method to print the struct's string representation:
func main() {
person := Person{name: "John Doe", age: 30}
fmt.Println(person) // This will automatically call the String() method
}
By embedding the fmt.Stringer
interface in your custom struct and implementing the String()
method, you can customize the string representation of the struct when it needs to be converted to a string using fmt.Println()
or any other function that expects a string argument.