英文:
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, "")
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
得分: 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论