Home >Backend Development >Golang >Is Pointer Arithmetic Possible in Go, and Why Is It Discouraged?
Pointer Arithmetic in Go
Unlike in C, pointer arithmetic is not possible in Go. As stated in the Go FAQ, the absence of pointer arithmetic enhances safety by eliminating the possibility of deriving illegal addresses. Additionally, modern compilers and hardware allow array index loops to match the efficiency of pointer arithmetic loops.
Despite this restriction, it is technically feasible to perform pointer arithmetic using the unsafe package. However, it is strongly discouraged due to potential risks. Consider the following example:
package main import ( "fmt" "unsafe" ) func main() { vals := []int{10, 20, 30, 40} start := unsafe.Pointer(&vals[0]) // Pointer to the first element size := unsafe.Sizeof(int(0)) // Size of an int in bytes for i := 0; i < len(vals); i++ { item := *(*int)(unsafe.Pointer(uintptr(start) + size*uintptr(i))) // Dereference the pointer at the correct offset fmt.Println(item) } }
While this code appears to perform pointer arithmetic, it should be emphasized that using the unsafe package can lead to undefined behavior and should only be considered in exceptional cases. To avoid potential risks, it is recommended to utilize Go's built-in array indexing or other safe alternatives.
The above is the detailed content of Is Pointer Arithmetic Possible in Go, and Why Is It Discouraged?. For more information, please follow other related articles on the PHP Chinese website!