Go vet complains about this minimal example code
type Foo struct {
val atomic.Uint64
}
func main() {
var foos = make([]Foo, 0)
var bar Foo
bar.val.Store(5)
foos = append(foos, bar) // call of append copies lock value:
example.com/foo.Foo contains sync/atomic.Uint64 contains sync/atomic.noCopy
}
Because the types of the sync package are not supposed to be copied.
This is also true for sync.Map, sync.Mutex, sync.WaitGroup etc.
However, if I instead copy in a zero-value Foo and then set that, go vet
does not complain, even if later appends are done:
func main() {
var foos = make([]Foo, 0)
foos = append(foos, Foo{})
foos[0].val.Store(5)
foos = append(foos, Foo{})
foos = append(foos, Foo{})
// append some more
// ...
fmt.Println(foos)
}
However, is this supposed to be safe, or is go vet just not catching it?
Even if copying a zero-value of such a type is safe, append() might have to
re-allocate the underlying array, which includes copying the existing
values, which might already have been used, as foo[0] has been in this
case. This would violate the noCopy trait of the type. My question is thus:
Is it safe to keep nocopy types from the sync and sync.atomic packages in a
slice, given that they might internally be copied when the slice is
appended to?
Of course, copying these types is not by itself atomic or synchronized with
other accesses. So let's assume that I, as the programmer, guarantee that
while an append happens, this slice will only be accessed by the one
appending goroutine, using other synchronization primitives, such as mutex,
channels etc. or by only running these appends in the main before any other
go-routine is started.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/31e8d7c2-9198-4ea7-99c9-ed56e13d32c3n%40googlegroups.com.