Setting an Int Pointer to an Int Value in Go
When trying to assign a value to a pointer variable, it's crucial to ensure the pointer is not nil. Attempting to dereference a nil pointer can lead to a runtime panic, as you experienced.
Solution:
To set the pointed value, the pointer must point to something valid. You can obtain a pointer to a zero-valued int using the new() function:
guess := new(int) *guess = 12345
This allocates memory for the int variable and sets the pointer to point to that memory. Now you can modify the pointed value through the pointer.
Simplified Declaration:
You can simplify the declaration and initialization using a short variable declaration:
guess := new(int) *guess = 12345
Alternative Approach:
You can also assign the address of an existing variable to the pointer:
value := 12345 guess := &value
This modifies the pointer value, not the pointed value. However, in this simple example, the effect is similar.
Modification of Pointed Value:
Changing the pointed value through the pointer will also change the value of the variable it points to. Conversely, modifying the value of the variable will affect the pointed value:
var value int guess := &value value = 12345 fmt.Println(*guess) // Prints: 12345
Using a pointer provides a convenient way to indirectly modify the value of a variable. However, it's important to initialize the pointer properly to avoid nil pointer errors and ensure data integrity.
The above is the detailed content of How to Safely Assign an Integer Value to an Integer Pointer in Go?. For more information, please follow other related articles on the PHP Chinese website!