当试图访问作为另一类型地址的结构的属性时,我正在尝试找到捕获nil pointer dereference
的最佳方法。
假设我们有这些结构(代码仅用于演示。我的意图是传达一点(
type Location struct {
coordinates *Coordinates
}
type Coordinates struct {
lat *Latitude
lon *Longitude
}
type Latitude struct {
lat float64
}
type Longitude struct {
lon float64
}
初始化空位置并访问loc.coordinates.lat
显然会产生预期的错误
loc := Location{}
fmt.Println(loc.coordinates.lat) // runtime error: invalid memory address or nil pointer dereference
为了解决这个问题,我可以做
if loc.coordinates != nil {
fmt.Println(loc.coordinates.lat)
}
但在这种情况下,如果我想打印出Latitude
的lat
属性,我必须添加另一个if
语句,如下所示
if loc.coordinates != nil {
if(loc.coordinates.lat != nil){
fmt.Println(loc.coordinates.lat.lat)
}
}
我想知道是否有其他方法可以在不检查每个地址是否不等于nil
的情况下处理这种情况。Go中有类似val, ok := someMap["foo"]
的结构吗?
如果定义指针类型,则必须处理它们可能为零的情况。一种方法是检查每个访问。另一种方法是使用可以处理零接收器的getter:
func (c *Coordinates) GetLat() (Latitude,bool) {
if c==nil {
return Latitude{}, false
}
return c.lat,true
}
func (l *Location) GetCoordinates() *Coordinates {
if l==nil {
return nil
}
return l.coordinates
}
lat, ok:=l.GetCoordinates().GetLat()
if ok {
// there is a valid lat
}
我正在考虑是否有其他方法可以处理这种情况,而不检查每个地址是否都不等于零。
不,没有。(从产生的恐慌中恢复是一种糟糕的做法,容易出错且速度缓慢。(
在Go for structs中有类似val,ok:=someMap的东西吗?
否。