Start learning free

LESSON 611 OF 639 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in Go in Go

Lesson

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 old
STEP 1 OF 2
    Ctrl + Enter to check

    Printing Objects in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free