map[string]*type "invalid memory address or nil pointer dereference"

2.3k Views Asked by At

When i try to access the struct field i got an error

invalid memory address or nil pointer dereference. gdreport/main.go:30 +0x1e6

i have no clue about the error:

here is my code:

var strPtr []*string

var findingId []string = []string{"findingid"}

strPtr = aws.StringSlice(findingId)

maxResult := int64(8)

condition := map[string]*guardduty.Condition{}
condition["id"].Equals = strPtr

line 30 condition["id"].Equals = strPtr

aws sdk for golang https://docs.aws.amazon.com/sdk-for-go/api/service/guardduty/#Condition type

1

There are 1 best solutions below

0
kozmo On

Because condition is the empty map of pointers, you get nil value of *guardduty.Condition from condition.

According Go maps in action:

A two-value assignment tests for the existence of a key:

i, ok := m["route"]

In this statement, the first value (i) is assigned the value stored under the key "route". If that key doesn't exist, i is the value type's zero value (0). The second value (ok) is a bool that is true if the key exists in the map, and false if not.

Change your code snippet to

if cond, ok := condition["id"]; !ok { // <nil> false
    log.Println("Pointer is null")
} else {
    // Init new guardduty.Condition
    // and assign to required key
    nc := &guardduty.Condition{Equals:strPtr}
    condition["id"] = nc
}