Implement the String() method on your type to satisfy the fmt.Stringer interface for custom formatting.
Implement the String() method on your custom type to satisfy the fmt.Stringer interface.
type MyType struct {
Value int
}
func (m MyType) String() string {
return fmt.Sprintf("MyType(%d)", m.Value)
}
This allows fmt.Print and fmt.Sprintf to automatically call your method when formatting the type.
The Stringer interface is a simple contract that lets your custom data types decide how they look as text. When you implement it, Go automatically uses your custom formatting whenever you print the variable, just like how a person introduces themselves by name instead of listing their DNA.