After the go pointer is declared and assigned, a panic: runtime error: invalid memory address or nil pointer reference appears

pointer basics
package main

import "fmt"

func main() {
	var p *int
	p = new(int)
	*p = 1
	fmt.Println(p, &p, *p)
}

Output
0xc04204a080  0xc042068018  1

Go * represents the value stored in the pointer address, & is the address to take a value. For the pointer, it’s important to understand that the pointer stores the address of a value, but the pointer itself also needs the address to store
As above p is a pointer whose value is memory address 0xc04204a080</code b> and p memory address 0xc042068018 memory address 0xc04204a080 memory address 0 11
The

error instance

In golang if we define a pointer and assign it to it like a normal variable, such as the code below

package main

import "fmt"
func main() {
	var i *int
	*i = 1
    fmt.Println(i, &i, *i)
}

Would have reported such an error

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x0 pc=0x498025]

The reason for this error is that go when you initialize the pointer it gives the pointer I and it gives the pointer nil, but I is the address of * I , 0 nil1 the system doesn’t give the address of 2 * I 3, So there’s definitely an error in assigning * I and it’s very easy to solve this problem, you can just create a block of memory to allocate to an assignment object before you assign to a pointer

package main

import "fmt"
func main() {
	var i *int
	i = new(int)
	*i = 1
	fmt.Println(i, &i, *i)
}


Read More: