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


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

在Go語言中,原子包提供較低級別的原子內存,這對實現同步算法很有幫助。 Go語言中的Store()函數用於將Value的值設置為x(即interface)。並且所有對Store方法的調用都必須使用相同具體類型的值來實現。此外,矛盾類型的商店將引起恐慌。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。

用法:

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

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

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

返回值:它存儲提供的值,並可以在需要時加載。



範例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!") 
}

輸出:

Any type of value is stored!

在上麵的示例中,我們使用了值類型來存儲任何類型的值。這些值存儲在所聲明的接口r1處。

範例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") 
}

輸出:

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

這裏,上麵存儲的值具有不同的具體類型,因此稱為恐慌。




相關用法


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