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: incrementdogCount, then returnDog{name: name}. - Create
rexandbuddywithNewDogand printdogCountinmainFunction. - 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, createsLuna, 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)
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
