TL ; DR:
Give your type a String() string method. Then fmt.Println prints the text it returns.
type Cat struct {
name string
}
func (this Cat) String() string {
return "Cat named " + this.name
}
// fmt.Println(Cat{name: "Tom"}) prints Cat named Tom
Full lesson:
fmt.Println can print any struct. By default, it shows the field values in braces:
{Tom}
That is often not what a reader needs.
The fmt package has an interface for this, fmt.Stringer. It has one method, String() string. Any type with that method satisfies it, as you saw with interfaces.
Before fmt prints a value, it checks for that method. If the value has it, fmt prints what it returns.
The name must be exactly String, with a capital S. It takes no parameters and returns a string. It must return the text, not print it.
Use a value receiver, as in (this Cat). Then a Cat prints with it, and so does a pointer to one.
Your task
The Dog struct below has a name and an age. Give it a String method.
It returns the name, then " is ", the age and " years old". The code in mainFunction prints two dogs.
Expected output:
Rex is 3 years old
Bella is 5 years oldFree plan: 30 tutor messages. Premium is unlimited.
