'How to initialize a struct which has a pointer-type property?
The struct is like this:
type Node struct {
Stat *Stat
}
type Stat struct {
StatInfo []string
}
Initialize the structure, and set properties.
node := new(Node)
node.Stat.Statinfo=strings.Split(somestr," ")
program calls panic:
panic: runtime error: invalid memory address or nil pointer dereference
Solution 1:[1]
When you create a struct, it's fields default to the zero value of their corresponding type. It's 0
for int
, nil
for pointer fields, etc.
In your case, the only field Stat
is a pointer, after calling new(Node)
, node.Stat
is nil
, so it would result in the runtime error you see.
To avoid the error, make sure you initialize the fields before accessing them.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter |