索引数组的一部分

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.

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.