duanchi19820419 2017-08-24 12:36
浏览 19
已采纳

索引数组的一部分

I'm a total golang (1.8) n00b trying to quickly index part of an array. This is what I tried:

 8:   data := make([]byte, 10)
 9:   row := &data[3]
10:   fmt.Println(row[0])

The build error is:

10: invalid operation: row[0] (type *byte does not support indexing)

Gold star if you also know if there are any parallel primitives (mutex?) when accessing the data array, which could slow down writes, as opposed to letting each goroutine allocate an array of its own.

  • 写回答

1条回答 默认 最新

  • dslf46995 2017-08-25 07:25
    关注

    First off, I would suggest reading this Go blog post to clarify the difference between arrays and slices.

    Simply put:

    • Arrays are a numbered sequence of elements.
    • Slices contains a pointer to an underlying array element, a length and a capacity.

    What you normally do with pointer arithmetic in languages like C, you do with slices in Go. Actually, you very seldom use arrays directly in Go.

    Slicing

    In your example, you can do the following:

    data := make([]byte, 10) // Create a slice with length of 10
    row := data[3:]          // Slicing a new slice starting from index 3. Length is 6
    row[0] = 42
    fmt.Println(data[3])
    

    Output:

    42

    Using slicing, you pass different sections of an underlying array/slice to different Go routines to work on, without any races.

    But if you instead want to have them work on the same slice, you can always protect it with a sync.Mutex instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题