http://play.golang.org/p/jdWZ9boyrh
我收到了这个错误
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]
Run Code Online (Sandbox Code Playgroud)
当我的函数尝试接收结构数组时.
一个未命名的类型是什么意思?为什么不能命名?我可以在函数外面命名它,并将它们作为参数传递给它们命名.
这是行不通的.所以我只是将[] 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)
//Expecting [{0 C} {1 C} {2 C} {3 C} {4 C}]
//but not working
Run Code Online (Sandbox Code Playgroud)
它与[]句子无关.
反正我是否可以使函数接收Struct数组?
我仍在学习 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"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4313 次 |
| 最近记录: |