atomic.Store() Function in Golang With Examples
Last Updated :
01 Apr, 2020
In Go language, atomic packages supply lower level atomic memory that is helpful is implementing synchronization algorithms. The Store() function in Go language is used to set the value of the Value to x(i.e, interface).
And all the calls to Store method for a stated Value should use values of an identical concrete type. Moreover, Store of a contradictory type will call panic. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func (v *Value) Store(x interface{})
Here, v is the value of any type and x is the interface which is the output result type of Store method.
Note: (*Value) is the pointer to a Value type. And Value type supplied in the sync/atomic standard package is used to atomically store as well as load values of any type.
Return value: It stores the value provided and can be loaded when required.
Example 1:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
type L struct { x, y, z int }
var r1 = L{9, 10, 11}
var V atomic.Value
V.Store(r1)
fmt.Println( "Any type of value is stored!" )
}
|
Output:
Any type of value is stored!
In the above example, we have used Value type in order to store the values of any type. And these values are stored at r1 which is the interface stated.
Example 2:
package main
import (
"sync/atomic"
)
func main() {
type L struct { x, y, z int }
var r1 = L{9, 10, 11}
var V atomic.Value
V.Store(r1)
V.Store( "GeeksforGeeks" )
}
|
Output:
panic: sync/atomic: store of inconsistently typed value into Value
goroutine 1 [running]:
sync/atomic.(*Value).Store(0x40c018, 0x99a40, 0xb23e8, 0x40e010)
/usr/local/go/src/sync/atomic/value.go:77 +0x160
main.main()
/tmp/sandbox206117237/prog.go:31 +0xc0
Here, the value stored above is of different concrete type so panic is called.
Share your thoughts in the comments
Please Login to comment...