英文:
Is it ok to use slices as shared memory?
问题
在这样的构造中使用切片是否可以呢:
type buffer struct {
values []int
mutex sync.RWMutex
}
我问这个问题是因为当我们向切片追加元素时,有可能会将切片复制到内存中的新位置。
英文:
Is it ok to use slices in a construction like this:
type buffer struct {
values []int
mutex sync.RWMutex
}
I ask because when we append to slice, there is a chance that we will copy the slice to the new place in memory.
答案1
得分: 3
在大多数Go编程中,人们通常会将切片重新赋值给原变量,而不会担心性能问题,因为切片是引用值。
b.values = append(b.values, i)
type buffer struct {
values []int
mutex sync.RWMutex
}
func (b *buffer) Append(i int) {
b.mutex.Lock()
b.values = append(b.values, i)
b.mutex.Unlock()
}
英文:
In most Go programming, people will assign slice back without performance concern in case append
returns new memory since slices are reference value.
b.values = append(b.values, i)
type buffer struct {
values []int
mutex sync.RWMutex
}
func (b *buffer) Append(i int) {
b.mutex.Lock()
b.values = append(b.values, i)
b.mutex.Unlock()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论