Go forbids direct pointer arithmetic for safety, requiring the unsafe package for manual memory offset calculations.
No, you cannot perform pointer arithmetic directly on Go pointers. Go forbids adding integers to pointers or subtracting pointers from each other to prevent unsafe memory access. To achieve similar results, you must use the unsafe package to convert pointers to uintptr integers, perform the math, and convert back, though this is generally discouraged for safety reasons.
import "unsafe"
func addPointer(p unsafe.Pointer, offset uintptr) unsafe.Pointer {
return unsafe.Pointer(uintptr(p) + offset)
}
Go does not allow you to do math on memory addresses like C does because it wants to keep your program safe from crashing or corrupting data. If you absolutely need to calculate memory offsets, you have to use a special, unsafe tool that converts the address into a number, does the math, and turns it back into an address. Think of it like being allowed to measure the distance between two houses on a map, but not allowed to physically walk to a new house based on that calculation without a special permit.