英文:
Why can't range over *[]Struct?
问题
我正在获取这个错误:
prog.go:29: invalid receiver type *[]Sentence ([]Sentence is an unnamed type)
prog.go:30: cannot range over S (type *[]Sentence)
[process exited with non-zero status]
当我的函数尝试接收结构数组时。
什么是未命名类型的意思?为什么它不能被命名?我可以在函数外部给它命名,并且还可以将它们作为带有名称的参数传递。
但这样不起作用。所以我只是将 []Sentence 作为参数传递,并解决了我需要的问题。但是在传递它们作为参数时,我不得不返回一个新的副本。
我仍然认为,如果我可以让函数接收结构数组而不必返回任何东西,那将是很好的。
像下面这样:
func (S *[]Sentence)MarkC() {
for _, elem := range S {
elem.mark = "C"
}
}
var arrayC []Sentence
for i:=0; i<5; i++ {
var new_st Sentence
new_st.index = i
arrayC = append(arrayC, new_st)
}
//MarkC(arrayC)
//fmt.Println(arrayC)
//期望输出 [{0 C} {1 C} {2 C} {3 C} {4 C}]
//但是不起作用
使用 []Sentence 也不起作用。
有没有办法让函数接收结构数组?
英文:
http://play.golang.org/p/jdWZ9boyrh
I am getting this error
prog.go:29: invalid receiver type *[]Sentence ([]Sentence is an unnamed type)
prog.go:30: cannot range over S (type *[]Sentence)
[process exited with non-zero status]
when my function tries to receive structure array.
What does it mean by an unnamed type? Why can't it be named? I can name it outside function and also pass them as arguments with them being named.
It does not work. So I just passed []Sentence as an argument and solve the problem that I need to. But when passing them as arguments, I had to return a new copy.
I still think that it would be nice if I can just let the function receive the struct array and does not have to return anything.
Like below:
func (S *[]Sentence)MarkC() {
for _, elem := range S {
elem.mark = "C"
}
}
var arrayC []Sentence
for i:=0; i<5; i++ {
var new_st Sentence
new_st.index = i
arrayC = append(arrayC, new_st)
}
//MarkC(arrayC)
//fmt.Println(arrayC)
//Expecting [{0 C} {1 C} {2 C} {3 C} {4 C}]
//but not working
It is not working either with []Sentence.
Is there anyway that I can make a function receive Struct array?
答案1
得分: 4
我还在学习Go语言,但是似乎它需要给类型命名。你知道,“句子的数组” - 这实际上是一个匿名类型。你只需要给它命名。
(另外,使用for
循环或者range
的单变量形式可以避免复制元素(并丢弃你的更改))
type Sentence struct {
mark string
index int
}
type SentenceArr []Sentence
func (S SentenceArr)MarkC() {
for i := 0; i < len(S); i++ {
S[i].mark = "S"
}
}
英文:
I'm still learning Go but it seems that it wants the type named. You know, "array of sentences" - that is really an anonymous type. You just have to name it.
(also, use for
or one-variable form of range
to avoid copying elements (and discarding your changes))
type Sentence struct {
mark string
index int
}
type SentenceArr []Sentence
func (S SentenceArr)MarkC() {
for i := 0; i < len(S); i++ {
S[i].mark = "S"
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论