Open In App

atomic.Store() Function in Golang With Examples

Last Updated : 01 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:




// Program to illustrate the usage of
// Store function in Golang
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Defining a struct type L
    type L struct{ x, y, z int }
  
    // Defining a variable to assign
    // values to the struct type L
    var r1 = L{9, 10, 11}
  
    // Defining Value type to store
    // values of any type
    var V atomic.Value
  
    // Calling Store function
    V.Store(r1)
  
    // Printed if the value stated is stored
    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:




// Program to illustrate the usage of
// Store function in Golang
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Defining a struct type L
    type L struct{ x, y, z int }
  
    // Defining a variable to assign
    // values to the struct type L
    var r1 = L{9, 10, 11}
  
    // Defining Value type to store
    // values of any type
    var V atomic.Value
  
    // Calling Store function
    V.Store(r1)
  
    // Storing value of 
    // different concrete type
    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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads