I'm very new to Go and am trying to set a *int
to point to a number, say 12345
.
package main
import (
"fmt"
"reflect"
)
func main() {
var guess *int
fmt.Println(reflect.TypeOf(guess))
*guess = 12345
fmt.Println(guess)
}
But it's giving me the following error:
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
I see that the error is with the *guess = 12345
since 12345
, but I'm not sure what's causing it.
Assuming you really want an int pointer and not just an int, then you need a variable to store the int
you point to. For example:
var guess *int
a := 12345
guess = &a
You have a pointer variable which after declaration will be nil
.
If you want to set the pointed value, it must point to something. Attempting to dereference a nil
pointer is a runtime panic, just what you experienced. You may use the builtin new()
function to obtain a pointer to a zero-valued int
, and then you can set the pointed value:
var guess *int
guess = new(int)
*guess = 12345
Your modified app:
var guess *int
fmt.Println(guess)
guess = new(int)
*guess = 12345
fmt.Println(guess, *guess)
Output (try it on the Go Playground):
<nil>
0x10414028 12345
Note that you can make this shorter using a short variable declaration like this:
guess := new(int)
*guess = 12345
Another option to make a pointer point to something "useful" is to assign the address of a variable to the pointer variable, like this:
value := 12345 // will be of type int
guess := &value
But this solution modifies the pointer value, not the pointed value. The result is the same though in this simple example.
You could also just assign the address of another variable, and then proceed to change the pointed value:
var value int
guess := &value
*guess = 12345
Also note that since guess
points to value
, changing the pointed value will change the value of the value
variable too. Also if you change the value
variable directly, the pointed value by guess
also changes: they are one and the same:
var value int
guess := &value
value = 12345
fmt.Println(*guess) // This will also print 12345
Try this one on the Go Playground.
FWIW, if you do this often enough (like setting up data in unit tests) it's useful to have a shorthand, hence:
https://github.com/mwielbut/pointy
val := 42
pointerToVal := &val
// vs.
pointerToVal := pointy.Int(42)