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)
}
但在這種情況下,如果我想列印出我必須添加另一個陳述句如下的lat屬性Latitudeif
if loc.coordinates != nil {
if(loc.coordinates.lat != nil){
fmt.Println(loc.coordinates.lat.lat)
}
}
我想知道是否有任何其他方法可以在不檢查每個地址是否不等于nil. val, ok := someMap["foo"]在 Go for structs 中有什么類似的東西嗎?
uj5u.com熱心網友回復:
如果您定義指標型別,則必須處理它們可能為零。一種方法是檢查每個訪問。另一種方法是使用可以處理 nil 接收器的 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
}
uj5u.com熱心網友回復:
我想知道是否有任何其他方法可以在不檢查每個地址是否不等于 nil 的情況下處理這種情況。
不,沒有。(從產生的恐慌中恢復是一種不好的做法,容易出錯而且速度很慢。)
Go for structs 中有沒有類似 val, ok := someMap["foo"] 的東西?
不。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364099.html
標籤:走
上一篇:從Go/Golang服務器決議資料以意外的JSON格式回應獲取數字
下一篇:從結構標記驗證回傳自定義錯誤訊息
