处理 Golang 中循环中的 nil 列表

huangapple go评论81阅读模式
英文:

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)
			}
		}
	}
}

huangapple
  • 本文由 发表于 2022年8月27日 01:33:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/73504679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定