dreamfly0514 2015-07-06 23:00
浏览 13
已采纳

为什么我不能在Golang地图中键入字符串?

I'm writing a function in go to remove duplicate characters in a string. Here is my approach. When I run the following test, why do I get this error? I'm new to Go and used to more dynamic languages like Ruby/Python.

panic: assignment to entry in nil map [recovered]
    panic: assignment to entry in nil map

source.go

func removeDuplicate(s string) string {
  var m map[string]int
    var c_string []string = strings.Split(s, "")
    for i :=0; i < len(c_string); i++ {
      m[c_string[i]] = 0
    }
    for i :=0; i < len(c_string); i++ {
      m[c_string[i]] = m[c_string[i]] + 1
    }
  var (
        result string = ""
    )
    for i :=0; i < len(c_string); i++ {
      if m[c_string[i]] < 1 {
      result  = result + c_string[i]
        }
    }
    return result
}

source_test.go

func TestRemoveDuplicateChars(t *testing.T) {
  got := removeDuplicateChars("abbcde")
    if got != "abcde" {
        t.Fatalf("removeDuplicateChars fails")
    }
}
  • 写回答

1条回答 默认 最新

  • doulang9521 2015-07-06 23:08
    关注

    Because you haven't actually initilize/allocated m, you've only declared it. Make this; var m map[string]int into m := map[string]int{}.

    Which does initilization and assignment both in the same statement. You could also add another line m = make(map[string]int) which would prevent the error though I personally prefer the compacted syntax.

    fyi your code is barfing on this line; m[c_string[i]] = 0, the error message should make sense when combining that with the information above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题