C语言的通用类型指针交换是相当简单的,只需要将指针类型统一转成void*即可,Golang也有一种类似的操作,但是稍微麻烦一点:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package main import ( "fmt" "sync/atomic" "unsafe" ) func swapPointer(readPointer *unsafe.Pointer, writePointer *unsafe.Pointer) { *writePointer = atomic.SwapPointer(readPointer, *writePointer) } func main() { var a int = 1 var b int = 2 var readPointer *int = &a var writePointer *int = &b fmt.Println(*readPointer) fmt.Println(*writePointer) swapPointer((*unsafe.Pointer)(unsafe.Pointer(&readPointer)), (*unsafe.Pointer)(unsafe.Pointer(&writePointer))) fmt.Println("------------") fmt.Println(*readPointer) fmt.Println(*writePointer) } |
Continue reading...