Start learning free

LESSON 29 OF 69 · OBJECT-ORIENTED PROGRAMMING

Static Members in Go: Package-Level Variables and NewDog

Practice Read the full explanation

TL;DR:

Go has no classes and no static. The equivalent of a shared class counter is a package-level variable: one copy that every function in the package sees. Go also has no constructors, so a function named NewDog builds the struct, and it is the place that counts.

You start with:

type Dog struct {
    name string
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Declare the package-level counter var dogCount int (it starts at 0).
  • Write func NewDog(name string) Dog: increment dogCount, then return Dog{name: name}.
  • Create rex and buddy with NewDog and print dogCount in mainFunction.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • After your lines, the program already in the editor creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with dogCount.

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)
}

STEP 1 OF 6
    Ctrl + Enter to check

    GO · OBJECT-ORIENTED PROGRAMMING

    Static Members in Go, explained

    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

    1. Declare var dogCount int above the functions. A variable outside every function is shared by all callers.
    2. Declare NewDog taking name string and returning a Dog. Write the closing brace with it. Go has no constructors, so a New... function plays that role.
    3. Increment inside it: dogCount++ goes before the return. Every call reaches the same variable.
    4. In mainFunction, create rex with NewDog("Rex"). The counter becomes 1.
    5. Create buddy with NewDog("Buddy"). The counter becomes 2.
    6. Print dogCount with fmt.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 int is 0 without an assignment. Printing it before any dog is created shows 0.
    • Unused variables are errors, package-level ones are not. An unused local variable stops the build, which is why rex and buddy are followed by _ = rex and _ = buddy. Those lines count as a use. The package-level dogCount is 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 inside NewDog.
    • dogCount++ is a statement. In Go, ++ cannot be used inside an expression, so you cannot write x := 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. dogCount and name start with a lower-case letter, so code in other packages cannot touch them. NewDog starts with a capital and is visible outside the package.
    • Value, not pointer. NewDog returns a Dog, a copy of the struct. Copying a Dog later does not change dogCount, because only NewDog increments 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 use NewDog, so the count is only as reliable as the convention.
    • Shadowing the counter. Writing dogCount := 0 inside NewDog declares 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++ in mainFunction after each call works for that one program but counts nothing for dogs created elsewhere. Counting inside NewDog keeps the rule in one place.
    • Counting the starting state. The counter shows 0 before the first call, so the first NewDog brings it to 1, not 2.
    • Concurrent use. A plain int shared by several goroutines that call NewDog at the same time is a data race. For the single-threaded lesson that is irrelevant, but real code would need a mutex or the sync/atomic package.

    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.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free