如何将切片和数组合并到映射中

我正在尝试在Go中创建一个莫尔斯电码映射。我该怎么做?如果这样更容易,我还可以将一个切片转换为数组。


   alphabet := []string{}

    for i := 'A'; i <= 'Z'; i++ {

        alphabet = append(alphabet, string(i))

    }

    fmt.Println(alphabet)

    

    morseSlice := [26]string{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}

    

    // convert to map that maps letters to morse

    var morseDict map[string]string

    

    for i := 0; i > len(morseSlice); i++ {

        morseDict[alphabet[i]] = morseSlice[i]

    }

    

    fmt.Println(morseDict)

但我的地图是空的。我做错了什么?


jeck猫
浏览 88回答 1
1回答

噜噜哒

您的代码将引发错误 。要解决此问题,您需要对其进行初始化。assignment to entry in nil mapelementMap&nbsp;:=&nbsp;make(map[string]string)&nbsp;//Initialize并且您的条件应更改为,或者您可以使用less thanrangefor&nbsp;i,&nbsp;ele&nbsp;:=&nbsp;range&nbsp;alphabet&nbsp;{ &nbsp;&nbsp;elementMap[ele]&nbsp;=&nbsp;morseSlice[i] }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go