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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程