How to safely convert a pointer to *unsafe.Pointer

54 views
Skip to first unread message

ju...@sqreen.io

unread,
Jul 19, 2019, 7:33:05 PM7/19/19
to golang-nuts
Hello,

I would like to make sure that the following line of Go is a defined behavior:

 addr := (*unsafe.Pointer)((unsafe.Pointer)(&ptr))

I use it to perform atomic loads and stores to addr such as in this simple example: https://play.golang.org/p/DpDrRvTYMG8
It allows me not to use atomic.Value which performs two atomic operations and possible disable preemption (https://golang.org/src/sync/atomic/value.go?s=1233:1269#L35).

Thanks for your help,
Julio

Ian Lance Taylor

unread,
Jul 19, 2019, 8:28:48 PM7/19/19
to ju...@sqreen.io, golang-nuts
Yes, that operation is defined. As documented at
https://golang.org/pkg/unsafe, you can use unsafe.Pointer to convert
from a pointer to one type to a pointer to a different type.

Ian
Reply all
Reply to author
Forward
0 new messages