I'm trying to use a map[string]int
to count elements in a test in Go, but the values inside my map are always 0
:
var counts = make(map[string]int)
func mockCheckTokenExists(counts map[string]int) func(token string) (bool, error) {
return func(token string) (bool, error) {
fmt.Println("count: ", counts[token])
if token == tokenPresent0Times {
return false, nil
} else if token == tokenPresent1Times && counts[tokenPresent1Times] == 1 {
return false, nil
}
counts[token]++;
return true, nil
}
}
the function returned by this one is passed as parameter to another one.
when printing the counts at each call they are always 0. What is wrong with this code?
You have not provided us with a reproducible example: How to create a Minimal, Complete, and Verifiable example..
This seems to work,
package main
import "fmt"
var counts = make(map[string]int)
var tokenPresent0Times, tokenPresent1Times string
func mockCheckTokenExists(counts map[string]int) func(token string) (bool, error) {
return func(token string) (bool, error) {
fmt.Println("count: ", counts[token])
if token == tokenPresent0Times {
return false, nil
} else if token == tokenPresent1Times && counts[tokenPresent1Times] == 1 {
return false, nil
}
counts[token]++
return true, nil
}
}
func main() {
fn := mockCheckTokenExists(counts)
fn("atoken")
fn("atoken")
fmt.Println(counts)
}
Output:
count: 0
count: 1
map[atoken:2]
What are you doing differently?