为什么不能对*[]Struct进行范围遍历?

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

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 = &quot;C&quot;
  }
}

var arrayC []Sentence
for i:=0; i&lt;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 &lt; len(S); i++ {
    S[i].mark = &quot;S&quot;
  }
}

huangapple
  • 本文由 发表于 2013年11月7日 13:32:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/19828652.html
匿名

发表评论

匿名网友

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

确定