R
R
RoadToGamedev2020-11-03 23:29:58
go
RoadToGamedev, 2020-11-03 23:29:58

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

2 answer(s)
E
Evgeny Samsonov, 2020-11-04
@RoadToGamedev

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

https://play.golang.org/p/6JdUk4hwtjU

D
Dasha Tsiklauri, 2020-11-04
@dasha_programmist

https://gobyexample.com/atomic-counters

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question