當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang atomic.Load()用法及代碼示例

在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的Load()函數用於檢查由Store方法存儲的最新值的值集。此外,如果尚未對此Value進行對Store方法的調用,它也可以返回nil。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。

用法:

func (v *Value) Load() (x interface{})

在這裏,v是任何類型的值,x是接口,它是Load以及Store方法的輸出結果類型。

注意:(* Value)是指向Value類型的指針。同步/原子標準包中提供的值類型用於原子加載和存儲任何類型的值。

返回值:它返回由store方法存儲的值集。如果未調用store方法,也可以返回nil。



範例1:

// Program to illustrate the usage of 
// Load 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) 
  
    // Calling Load method 
    var r2 = V.Load().(L) 
  
    // Prints values as 
    // stored by recent 
    // store method 
    fmt.Println(r2) 
  
    // Displays true if satisfied 
    fmt.Println(r1 == r2) 
}

輸出:

{9 10 11}
true

在上麵的示例中,我們使用了值類型來存儲任何類型的值。這些值存儲在所聲明的接口r1處。但是,可以使用Load方法返回這些值。

範例2:

// Program to illustrate the usage of 
// Load 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 Load method 
    var r2 = V.Load().(L) 
  
    // Prints values as  
    // stored by recent 
    // store method 
    fmt.Println(r2) 
  
    // Displays true if satisfied 
    fmt.Println(r1 == r2) 
}

輸出:

panic:interface conversion:interface {} is nil, not main.L

goroutine 1 [running]:
main.main()
    /tmp/sandbox731326366/prog.go:28 +0x240

在這裏,沒有調用store方法,因此返回nil。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 atomic.Load() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。