英文:
Go: integers in maps always 0
问题
我正在尝试在Go中使用map[string]int
来计算测试中的元素数量,但是我的映射中的值始终为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
}
}
通过这个函数返回的函数作为参数传递给另一个函数。
在每次调用时打印计数时,它们始终为0。这段代码有什么问题?
英文:
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?
答案1
得分: 4
您没有提供一个可重现的示例:如何创建一个最小、完整和可验证的示例。
这段代码似乎是有效的:
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)
}
输出结果为:
count: 0
count: 1
map[atoken:2]
您有什么不同的操作?
英文:
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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论