英文:
Handle nil in loop from list Golang
问题
我正在循环遍历从后端接收到的一些数据,其中可能包含一个空值,在程序中会出现“panic: runtime error: invalid memory address or nil pointer dereference”错误。
我该如何处理空值?我想将空值设置为“EMPTY”。
我尝试了以下代码,但仍然会出错:
for _, res := range resp.Autombiles {
for _, trk := range res.Trucks {
if trk == nil {
println("EMPTY")
} else {
println(*trk.EngineType)
}
}
}
}
这是我的循环代码:
for _, res := range resp.Autombiles {
for _, trk := range res.Trucks {
fmt.Println(*trk.EngineType)
}
}
}
英文:
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)
}
}
}
答案1
得分: 1
看起来res.Trucks
是空的。所以在创建trk
变量之前,你的程序会崩溃,就在这里:for _, res := range res.Trucks{}
for _, res := range resp.Autombiles {
// res.Trucks 可能为空
for _, trk := range res.Trucks {
...
}
}
所以,在res.Trucks
存在的情况下添加一个检查:
for _, res := range resp.Autombiles {
if res.Trucks != nil {
for _, trk := range res.Trucks {
if trk == nil || trk.EngineType == nil {
println("EMPTY")
} else {
println(*trk.EngineType)
}
}
}
}
英文:
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 || trk.EngineType == nil {
println("EMPTY")
} else {
println(*trk.EngineType)
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论