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 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致