TL ; DR:
A constructor is a special function that runs when you create an object. It's used to set up the object's initial state.
In Go, the convention is to write a
NewXxxfunction that takes parameters and returns an initialized struct:type Dog struct { name string age int } func NewDog(name string, age int) Dog { return Dog{name: name, age: age} }
Then create objects with arguments:
rex := NewDog("Rex", 4)— the constructor function fills in the fields for you.
Full lesson:
In the previous lesson you set member variables one at a time after creating the object:
var dog Dog
dog.name = "Rex"
dog.age = 4
That works, but it's verbose and easy to forget. Constructor functions let you initialize the fields the moment the object is created.
Defining a constructor
A Go constructor is a regular function with two distinguishing features:
By convention, its name starts with
Newfollowed by the type name (NewDogfor aDogstruct).It returns the struct type — Go constructor functions return an initialized value.
func NewDog(name string, age int) Dog {
return Dog{name: name, age: age}
}
Struct literal initialization
Inside the constructor, Go uses a struct literal Dog{name: name, age: age} to build the value. The left-hand name is the field name, and the right-hand name is the parameter — there is no ambiguity because Go uses named fields rather than a this pointer.
Calling the constructor
rex := NewDog("Rex", 4)
luna := NewDog("Luna", 7)
By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.
Your task
The Dog struct already has the name and age fields. Add a NewDog constructor function that takes a name string and an age int and returns an initialized Dog. Then in mainFunction, create two dogs:
rex := NewDog("Rex", 4)
luna := NewDog("Luna", 7)
Expected output:
Rex is 4
Luna is 7Free plan: 30 tutor messages. PRO is unlimited.
