Setting an Int Pointer to an Int Value in Go
In Go, a common task is assigning a value to an int pointer. However, a recently discovered error in a code snippet sheds light on a potential pitfall:
package main import ( "fmt" "reflect" ) func main() { var guess *int fmt.Println(reflect.TypeOf(guess)) *guess = 12345 fmt.Println(guess) }
When executing this code, the following error occurs:
Type: *int panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x483c7d] goroutine 1 [running]: main.main() /home/aaron/projects/gopath/src/github.com/AaronNBrock/go-guess/main.go:16 +0x9d exit status 2
The root cause lies in the fact that the pointer guess is initially set to nil. Dereferencing a nil pointer throws a runtime error, as seen in the error message. The solution lies in allocating memory for the pointer before attempting to assign a value to it:
var guess *int guess = new(int) *guess = 12345
This modification ensures that guess points to a valid memory location, allowing us to set and retrieve its value.
Alternatively, using a short variable declaration can simplify the code:
guess := new(int) *guess = 12345
Another approach is to assign the address of an existing variable to the pointer:
value := 12345 // will be of type int guess := &value
This solution points guess to an existing variable, rather than allocating new memory. Changing the pointed value also modifies the value of the original variable.
Finally, keep in mind that pointing a pointer to a location and assigning a value to it are distinct operations. The former allocates memory or sets the pointer to an existing variable, while the latter modifies the value stored at the pointed location.
The above is the detailed content of How to Correctly Assign a Value to an Int Pointer in Go?. For more information, please follow other related articles on the PHP Chinese website!