Problem overview
Many languages let a class keep data that belongs to the class rather than to any one object, usually with the keyword static. Go has no classes and no static. The same idea, one value shared by every object, is written as a variable declared at package level, outside every function. Go also has no constructors, so by convention a function named NewDog builds the struct, and that function is the natural place to count.
The lesson starts with type Dog struct { name string } and asks for a counter of how many Dog values have been created. You declare dogCount, write NewDog, create rex and buddy, and print the counter. The code already in the editor then creates Max, prints the counter and Max's name, creates Luna, and prints the counter again. The expected output is:
2
3
Max
4
Approach: one variable, one place that changes it
A package-level variable exists once for the whole program. Every function in the package sees the same dogCount, so it behaves like a static field. An int starts at 0 in Go, so no initial value is needed, and the counter is 0 before any dog exists.
To keep the count right, the increment must happen in exactly one place, and it should happen every time a dog is built. That is the job of NewDog: it adds 1 to dogCount, then returns the new struct. As long as every dog is created through NewDog, the counter goes up by exactly one per dog, whatever its name.
Step by step
- Declare
var dogCount intabove the functions. A variable outside every function is shared by all callers. - Declare
NewDogtakingname stringand returning aDog. Write the closing brace with it. Go has no constructors, so aNew...function plays that role. - Increment inside it:
dogCount++goes before thereturn. Every call reaches the same variable. - In
mainFunction, createrexwithNewDog("Rex"). The counter becomes 1. - Create
buddywithNewDog("Buddy"). The counter becomes 2. - Print
dogCountwithfmt.Println. It shows 2.
The solution in Go
type Dog struct {
name string
}
var dogCount int
func NewDog(name string) Dog {
dogCount++
return Dog{name: name}
}
func mainFunction() {
rex := NewDog("Rex")
buddy := NewDog("Buddy")
_ = rex
_ = buddy
fmt.Println(dogCount)
third := NewDog("Max")
fmt.Println(dogCount)
fmt.Println(third.name)
NewDog("Luna")
fmt.Println(dogCount)
}
Go details to notice:
- The zero value is ready to use.
var dogCount intis 0 without an assignment. Printing it before any dog is created shows0. - Unused variables are errors, package-level ones are not. An unused local variable stops the build, which is why
rexandbuddyare followed by_ = rexand_ = buddy. Those lines count as a use. The package-leveldogCountis not subject to that rule. - Calling a function and ignoring its result is allowed.
NewDog("Luna")as a statement creates a dog and discards it. The counter still goes up, because the increment is a side effect insideNewDog. dogCount++is a statement. In Go,++cannot be used inside an expression, so you cannot writex := dogCount++.- Keyed struct literal.
Dog{name: name}names the field being set. The same word is the parameter and the field name, which is legal. - Lower case means package-private.
dogCountandnamestart with a lower-case letter, so code in other packages cannot touch them.NewDogstarts with a capital and is visible outside the package. - Value, not pointer.
NewDogreturns aDog, a copy of the struct. Copying aDoglater does not changedogCount, because onlyNewDogincrements it.
Edge cases and common mistakes
- Bypassing the constructor. A dog built directly, as in
Dog{name: "Direct"}, is never counted. After the program above has finished, creating one that way still leaves the counter at 4. Go cannot force callers to useNewDog, so the count is only as reliable as the convention. - Shadowing the counter. Writing
dogCount := 0insideNewDogdeclares a new local variable that hides the package one. The local is incremented and thrown away, and the shared counter never changes. Assign to the package-level variable without:=. - Incrementing in the wrong place. Putting
dogCount++inmainFunctionafter each call works for that one program but counts nothing for dogs created elsewhere. Counting insideNewDogkeeps the rule in one place. - Counting the starting state. The counter shows 0 before the first call, so the first
NewDogbrings it to 1, not 2. - Concurrent use. A plain
intshared by several goroutines that callNewDogat the same time is a data race. For the single-threaded lesson that is irrelevant, but real code would need a mutex or thesync/atomicpackage.
Testing
Printing dogCount before mainFunction runs shows 0. Running mainFunction prints 2, 3, Max and 4, one per line, in that order. The counter ends at 4 for four dogs: Rex, Buddy, Max and Luna.
Key takeaways
- Go has no
static: a package-level variable is the shared state. - Go has no constructors: a
New...function builds the value and does the setup. - Put the update in the constructor function so every created value is counted.
