我正在尝试在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)但我的地图是空的。我做错了什么?
1 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
您的代码将引发错误 。要解决此问题,您需要对其进行初始化。assignment to entry in nil map
elementMap := make(map[string]string) //Initialize
并且您的条件应更改为,或者您可以使用less than
range
for i, ele := range alphabet { elementMap[ele] = morseSlice[i] }
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消