当前位置: > > > > 有没有办法在Golang中处理nil指针而不使用if/else?
有没有办法在Golang中处理nil指针而不使用if/else?
来源:stackoverflow
2024-04-29 17:15:32
0浏览
收藏
你在学习Golang相关的知识吗?本文《有没有办法在Golang中处理nil指针而不使用if/else?》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
问题内容
例如我有这段代码:
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?》的详细内容,更多关于的资料请关注米云公众号!
