首頁  >  文章  >  後端開發  >  有沒有辦法在Golang中處理nil指標而不使用if/else?

有沒有辦法在Golang中處理nil指標而不使用if/else?

PHPz
PHPz轉載
2024-02-10 14:54:09720瀏覽

有沒有辦法在Golang中處理nil指標而不使用if/else?

php小編柚子,你是否曾經在Golang程式設計中遇到過處理nil指標的困擾?你是否想知道是否有一種方法可以避免使用繁瑣的if/else語句來處理這個問題?答案是肯定的!在Golang中,我們可以利用一些技巧和特性來簡化對nil指標的處理,讓程式碼更簡潔優雅。接下來,我將為你詳細介紹這些方法,讓你在Golang程式設計中更加得心應手。

問題內容

例如我有這段程式碼:

type MyStruct struct {    
    ...
    MyField *MyOtherStruct
    ...
}

type MyOtherStruct struct {
    ...
    MyOtherField *string
    ...
}

// I have a fuction that receive MyOtherField as parameter
func MyFunc(myOtherField *string) {
    ...
}

// How can I avoid using if/else here
if MyStruct.MyField != nil {
    MyFunc((*MyStruct.MyField).MyOtherField)
} else {
    MyFunc(nil)
}

在我的範例中,我必須使用 if else 來處理 mystruct.myfield 是否為零。我想找到一種方法來縮短我的程式碼。

我想在javascript中找到類似 myfunc(mystruct.myfield ? (*mystruct.myfield).myotherfield : nil) 的方法。

解決方法

不,你不能做你以前在 js 中做的事情。它只是語法糖。但是,還有一些替代方案。

首先,你可以簡單地寫:

if mystruct.myfield != nil {
    myfunc(mystruct.myfield.myotherfield)
} else {
    myfunc(nil)
}

在某些情況下,編寫與指標接收器一起使用的 getter 可能是有意義的:

func (m *myotherstruct) getotherfield() *otherfieldtype {
   if m==nil {
      return nil
   }
   return m.otherfield
}

然後你可以這樣做:

MyFunc(MyStruct.MyField.GetOtherField())

這就是 grpc 產生 go 模型的方式。但這通常是不可取的。它隱藏了微妙的錯誤。最好明確並檢查你在哪裡使用它。

以上是有沒有辦法在Golang中處理nil指標而不使用if/else?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除