Answer the question
In order to leave comments, you need to log in
Golang what are the ways to create a counter?
Hello. What is the best way to create a counter inside a function? So that when we call it in a loop, we would add +1.
There can be multiple functions in a loop. Which are called at different time intervals. That is, the counter must be unique for each function.
Answer the question
In order to leave comments, you need to log in
Can be done with a closure
package main
import (
"fmt"
)
func main() {
funcWithCounter1 := funcWithCounter()
fmt.Println(funcWithCounter1())
fmt.Println(funcWithCounter1())
fmt.Println(funcWithCounter1())
funcWithCounter2 := funcWithCounter()
fmt.Println(funcWithCounter2())
fmt.Println(funcWithCounter2())
}
func funcWithCounter() func() int {
var counter int
return func() int {
// тут полезная работа
counter++
return counter
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question