gpt4 book ai didi

Go: map 中的整数始终为 0

转载 作者:数据小太阳 更新时间:2023-10-29 03:43:16 24 4
gpt4 key购买 nike

我正在尝试使用 map[string]int 来计算 Go 测试中的元素,但我的 map 中的值始终为 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。此代码有什么问题?

最佳答案

您没有向我们提供可重现的示例:How to create a Minimal, Complete, and Verifiable example. .

这似乎可行,

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]

你有什么不同之处?

关于Go: map 中的整数始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33680616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com