douxing6532 2015-11-12 20:22
浏览 43

执行:地图中的整数始终为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条回答 默认 最新

  • duanli9591 2015-11-12 21:07
    关注

    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?

    评论

报告相同问题?