为什么我不能在 Golang 的 map 中输入字符串?

huangapple go评论81阅读模式
英文:

Why can't I key in a string in Golang map?

问题

我正在写一个在Go语言中删除字符串中重复字符的函数。以下是我的方法。当我运行下面的测试时,为什么会出现这个错误?我是Go语言的新手,之前更多地使用动态语言如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")
	}
}

这个错误是因为你在使用map之前没有对其进行初始化。在Go语言中,map是一个引用类型,需要使用make函数进行初始化。你可以在函数开始的地方添加以下代码来初始化map

m := make(map[string]int)

这样就可以解决这个错误了。希望对你有帮助!

英文:

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, &quot;&quot;)
	for i :=0; i &lt; len(c_string); i++ {
	  m[c_string[i]] = 0
	}
	for i :=0; i &lt; len(c_string); i++ {
	  m[c_string[i]] = m[c_string[i]] + 1
	}
  var (
		result string = &quot;&quot;
	)
	for i :=0; i &lt; len(c_string); i++ {
	  if m[c_string[i]] &lt; 1 {
      result  = result + c_string[i]
		}
	}
	return result
}

source_test.go

func TestRemoveDuplicateChars(t *testing.T) {
  got := removeDuplicateChars(&quot;abbcde&quot;)
	if got != &quot;abcde&quot; {
		t.Fatalf(&quot;removeDuplicateChars fails&quot;)
	}
}

答案1

得分: 6

因为你实际上没有初始化/分配m,你只是声明了它。将var m map[string]int改为m := map[string]int{}

这样可以在同一语句中进行初始化和赋值。你也可以添加另一行m = make(map[string]int)来避免错误,不过我个人更喜欢简洁的语法。

顺便说一下,你的代码在这一行出错:m[c_string[i]] = 0,结合上面的信息,错误信息应该是有意义的。

英文:

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.

huangapple
  • 本文由 发表于 2015年7月7日 07:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/31257125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定