Home > Blockchain >  Handle nil in loop from list Golang
Handle nil in loop from list Golang

Time:08-28

I'm looping through some data received from a backend and might contain a nil in the middle, the program crashes with panic: runtime error: invalid memory address or nil pointer dereference

How can i handle the nil? Would like to set an nil to show "EMPTY"

I've tried this but still crashes:

    for _, res := range resp.Autombiles {
        for _, trk := range res.Trucks {
                if trk == nil {
                    println("EMPTY")
                } else {
                    println(*trk.EngineType)
                }
            }
        }
    }

Here's my loop:

    for _, res := range resp.Autombiles {
        for _, trk := range res.Trucks {
                fmt.Println(*trk.EngineType)
            }
        }
    }

CodePudding user response:

Looks like res.Trucks is nil. So your program crashes before trk variable is created, here. for _, res := range res.Trucks{}

for _, res := range resp.Autombiles {

    //       res.Trucks can be nil
    for _, trk := range res.Trucks {
            ...
    }
}

So, add a check for existance of res.Trucks

for _, res := range resp.Autombiles {
    if res.Trucks != nil {
        for _, trk := range res.Trucks {
            if trk == nil {
                println("EMPTY")
            } else {
                println(*trk.EngineType)
            }
        }
    }
}
  • Related