Using the unsafe package, we can also convert a numeric variable pointer to its C counterpart. This allows us to edit it directly in the C code:
package main
/*
void half(double* f) {
*f = *f/2;
}
*/
import "C"
import (
"fmt"
"math"
"unsafe"
)
func main() {
a := float64(math.Pi)
fmt.Println(a)
C.half((*C.double)(unsafe.Pointer(&a)))
fmt.Println(a)
}
The preceding example does exactly that; it halves the value of a in a C function, without copying and assigning the new value in Go.