卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35222本站已运行394

有没有办法在Golang中处理nil指针而不使用if/else?

有没有办法在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 模型的方式。但这通常是不可取的。它隐藏了微妙的错误。最好明确并检查你在哪里使用它。

卓越飞翔博客
上一篇: SQL COALESCE 函数不适用于 GORM
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏