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