In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapPointer() function in Go language is used to perform the compare and swap operation for a unsafe.Pointer value. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)
Here, addr indicates address, old indicates unsafe.Pointer value that is the old swapped value which is returned from the SwapPointer operation, and new is the unsafe.Pointer new value that will swap itself from the old swapped value.
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 returns true if swapping is accomplished else it returns false.
In the above example, Swapping is not performed as the old value here in the CompareAndSwapPointer() method must be the value returned from the SwapPointer() method but here old value is different so false is returned from the above code.