In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StorePointer() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import the “sync/atomic” package in order to use these functions.
Syntax:
func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)
Here, addr indicates address.
Note: (*unsafe.Pointer) is the pointer to a unsafe.Pointer value. And unsafe.Pointer type is helpful in enabling transitions between arbitrary types and builtin uintptr type. Moreover, unsafe is a package that is helpful in type safety of Go programs.
Return Value: It stores the val into *addr and then can be returned when required.
Example 1:
// Program to illustrate the usage of // StorePointer function in Golang // Including main package package main // importing fmt, // sync/atomic and unsafe import ( "fmt"
"sync/atomic"
"unsafe"
) // Defining a struct type L type L struct { x, y, z int }
// Declaring pointer // to L struct type var PL *L // Calling main func main() { // Defining *addr unsafe.Pointer
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
// Defining value
// of unsafe.Pointer
var px L
// Calling StorePointer and
// storing unsafe.Pointer
// value to *addr
atomic.StorePointer(
unsafepL, unsafe.Pointer(&px))
// Printed if value is stored
fmt.Println( "Val Stored!" )
} |
Output:
Val Stored!
Here, the value unsafe.Pointer is stored in *addr that’s why above code returns the stated output.
Example 2:
// Program to illustrate the usage of // StorePointer function in Golang // Including main package package main // importing fmt, // sync/atomic and unsafe import ( "fmt"
"sync/atomic"
"unsafe"
) // Defining a struct type L type L struct { x, y, z int }
// Declaring pointer to L struct type var PL *L // Calling main func main() { // Defining *addr unsafe.Pointer
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
// Defining value
// of unsafe.Pointer
var px = 54634763
// Calling StorePointer and
// storing unsafe.Pointer
// value to *addr
atomic.StorePointer(
unsafepL, unsafe.Pointer(&px))
// Prints the value of the
// address where val is stored
fmt.Println(&px)
} |
Output:
0xc0000b6010 // Can be different at different run times
Here, the stated unsafe.Pointer val is stored and the address of the stored val is returned here. Moreover, the address can be different at different run times.