atomic.Load() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The Load() function in Go language is used to check the value set of the most current values as stored by Store method. Moreover, it can also return nil if no calls to Store method has been done for this Value. 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) Load() (x interface{})
Here, v is the value of any type and x is the interface which is the output result type of Load as well as 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 load as well as store values of any type.
Return Value: It returns the value set stored by the store method. And can also return nil if store method is not called.
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)
var r2 = V.Load().(L)
fmt.Println(r2)
fmt.Println(r1 == r2)
}
|
Output:
{9 10 11}
true
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. However, these values can be returned using the Load method.
Example 2:
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
var r2 = V.Load().(L)
fmt.Println(r2)
fmt.Println(r1 == r2)
}
|
Output:
panic: interface conversion: interface {} is nil, not main.L
goroutine 1 [running]:
main.main()
/tmp/sandbox731326366/prog.go:28 +0x240
Here, no call to store method has been done so nil is returned.
Last Updated :
01 Apr, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...