duanjian4150 2016-12-10 17:29
浏览 26
已采纳

如何在一条指令中初始化golang映射?

This is my code:

var keys map[int]string
keys = make(map[int]string)

keys[1] = "aa"
keys[2] = "ab"
keys[3] = "ac"
keys[4] = "ba"
keys[5] = "bb"
keys[6] = "bc"
keys[7] = "ca"
keys[8] = "cb"
keys[9] = "cc"

Can I do the same thing in one statement and/or in one line?

  • 写回答

3条回答 默认 最新

  • douzhan5262 2016-12-10 17:31
    关注

    Yes, you can create a map with a single statement (called a composite literal in the spec):

    var keys = map[int]string{
        1: "aa",
        2: "ab",
        3: "ac",
        4: "ba",
        5: "bb",
        6: "bc",
        7: "ca",
        8: "cb",
        9: "cc",
    }
    

    Or, if you are inside of a function, you can use a short variable declaration:

    keys := map[int]string{
        1: "aa",
        2: "ab",
        3: "ac",
        4: "ba",
        5: "bb",
        6: "bc",
        7: "ca",
        8: "cb",
        9: "cc",
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?