在Go語言中,原子包提供lower-level原子內存,這對實現同步算法很有幫助。 Go語言中的SwapInt32()函數用於將新值自動存儲到* addr中,並返回先前的* addr值。此函數在原子包下定義。在這裏,您需要導入“sync/atomic”軟件包才能使用這些函數。
用法:
func SwapInt32(addr *int32, new int32) (old int32)
在此,addr表示地址。而new是新的int32值,而old是舊的int32值。
注意:(* int32)是指向int32值的指針。但是,int32包含從-2147483648到2147483647的所有帶符號的32位整數的集合。
返回值:它將新的int32值存儲到* addr中,並返回先前的* addr值。
範例1:
// Program to illustrate the usage of
// SwapInt32 function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Assigning value to int32
var x int32 = 5435435
// Using SwapInt32 method
// with its parameters
var old_val = atomic.SwapInt32(&x, 6365654)
// Prints new and old value
fmt.Println("Stored new value:",
x, ", Old value:", old_val)
}
輸出:
Stored new value: 6365654, Old value: 5435435
範例2:
// Program to illustrate the usage of
// SwapInt32 function in Golang
// Including main package
package main
// Importing fmt and sync/atomic
import (
"fmt"
"sync/atomic"
)
// Main function
func main() {
// Assigning value to int32
var m int32 = 1223344
var n int32 = 6122082
// Using SwapInt32 method with its parameters
var oldVal1 = atomic.SwapInt32(&m, 1223344)
var oldVal2 = atomic.SwapInt32(&n, 16677)
// Prints output
fmt.Println((oldVal1) == m)
fmt.Println((oldVal2) == n)
}
輸出:
true false
這裏,oldVal1等於“m”,因為要存儲在* addr中的新值與舊值相同,因此返回true,但是oldVal2不等於“n”,因為那裏的舊值與新分配的值不相似,因此,則返回false。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 atomic.SwapInt32() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。