Go – Why can’t range over *[]Struct

arraysgopointersstruct

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?

Best Solution

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"
  }
}