Start learning free

LESSON 280 OF 671 · FUNCTIONS & CLASSES

Creating Objects in Go

Lesson

TL ; DR:

  • An object is an instance of a struct type — a real, usable value made from the blueprint.


  • In Go, you create a value of a struct type with a struct literal. Put & in front to get a pointer to the new value:

    rex := &Dog{}
    

  • Each declaration creates a separate value, even if they all come from the same struct type.



Full lesson:

In the previous lesson you defined the Dog struct — the blueprint. But a blueprint isn't a dog. To get an actual dog you can interact with, you need to create an instance of the struct. An instance is also called an object.


Value-type objects

The simplest way to create an object in Go is to declare it like a regular variable, which gives you a plain Dog value:

var rex Dog

This creates a Dog value named rex. All fields are initialized to their zero values automatically. A plain Dog value can never be nil, so you can't compare it with nil.


Many objects from one struct

You can declare as many Dog values as you want, and each one is independent:

var rex Dog
var buddy Dog
var luna Dog

rex, buddy, and luna are all Dog values, but they're different objects. Modifying one won't affect the others.


Pointers to objects

A struct literal with & in front creates a new object and gives you a pointer to it (a *Dog). Each such literal creates a brand-new object, and Go's garbage collector cleans up when nothing points to it any more:

rex := &Dog{}

The built-in new(Dog) does the same thing. A pointer can be compared with nil, which is what the validation below does.


Your task

The Dog struct is already defined for you. Below it, create three Dog objects with &Dog{}, stored in variables named rex, buddy, and luna. The pre-filled validation will print one line per dog you've successfully created:

rex exists
buddy exists
luna exists
STEP 1 OF 3
    Ctrl + Enter to check