duanlu0386 2013-11-07 05:32
浏览 44
已采纳

为什么不能超出* [] Struct?

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条回答 默认 最新

  • drcmue4619 2013-11-07 05:38
    关注

    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"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器