Start learning free

LESSON 391 OF 404 · OBJECT-ORIENTED PROGRAMMING

Static Members in Go in Go

Practice

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

    Static Members in Go

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