英文:
Indexing part of a array
问题
我是一个完全不懂golang(1.8)的新手,试图快速索引数组的一部分。这是我尝试的代码:
8: data := make([]byte, 10)
9: row := &data[3]
10: fmt.Println(row[0])
构建错误是:
10: invalid operation: row[0] (type *byte does not support indexing)
如果您还知道在访问data
数组时是否有任何并行原语(互斥锁?),这可能会减慢写入速度,而不是让每个goroutine分配自己的数组,那就太好了。
英文:
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
得分: 1
首先,我建议阅读这篇Go博客文章,以澄清数组和切片之间的区别。
简单来说:
- 数组是一个有序的元素序列。
- 切片包含指向底层数组元素的指针,以及长度和容量。
在像C这样的语言中通常使用指针算术的地方,在Go中可以使用切片。实际上,在Go中很少直接使用数组。
切片操作
在你的例子中,你可以这样做:
data := make([]byte, 10) // 创建长度为10的切片
row := data[3:] // 从索引3开始切片,长度为6
row[0] = 42
fmt.Println(data[3])
输出:
42
使用切片,你可以将底层数组/切片的不同部分传递给不同的Go协程进行处理,而不会出现竞争条件。
但是,如果你希望它们在同一个切片上工作,你可以始终使用sync.Mutex
来保护它。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论