Set int Pointer to int Value Golang
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.
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
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)