When using atomic.Values it is important that the type being stored is 
consistent. Trying to store a different type in an atomic.Value will cause 
a panic

panic: sync/atomic: store of inconsistently typed value into Value

I've found that the way around this is to create a new instance of 
atomic.Value whenever I have reason to believe that the type to be stored 
has changed. In my program this can happen because I am storing an 
interface in the atomic.Value and the implementation of the interface may 
change.

Choosing the moment to create the new atomic.Value however can be tricky so 
I am now trying the following method:

1) Check the type of the existing stored value and the type of the new value
2) If they are the same then atomic.Value.Store() can be used
3) If they are not the same, then create a new instance of atomic.Value and 
store new value in that
4) Give the new atomic.Value the name of the old atomic.Value

This method means I no longer have to worry about when I create a new 
instance of atomic.Value - the new instance is created when the type check 
fails.

Example code.

https://play.golang.org/p/1gmI5eMdOcl

Now, this obviously requires knowledge of how interface{} is represented 
internally, which isn't great, but in principle is this a correctly working 
solution? (It seems to be to me but that doesn't really mean anything)

Does returning an atomic.Value from a function count as "copying" after 
first use?

Is this going to bite me in the future?

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/8893475a-ec61-4f78-9dc0-b80dda9e675an%40googlegroups.com.

Reply via email to