英文:
Is there a way to propagate the "nilness" of a variable in a chained call?
问题
我在Go语言中有以下代码:
checkItemState := action.Data.CheckItem.State
if checkItemState != "" {
    fmt.Printf("checklist item state: %s", action.Data.CheckItem.State)
}
现在,如果链中的任何项action.Data.CheckItem为nil/空,我会得到一个空指针解引用错误,这是有道理的。
但是,是否有一种语言级别的方法可以获取checkItemState,如果不为nil,则获取"",如果链中的任何项为nil/空。
(我来自Obj-C/Swift领域,那里的nil传播)
英文:
I have the following in Go:
checkItemState := action.Data.CheckItem.State
if checkItemState != "" {
			fmt.Printf("checklist item state: %s", action.Data.CheckItem.State)
}
Now if any of the items in the chain action.Data.CheckItem are nil/empty, I get a nil pointer dereference error, which makes sense.
But is there a language level way to get checkItemState if not nil, or "" if any of the items in the chain are nil/empty.
(I come from Obj-C/Swift land where the nilness propagates)
答案1
得分: 5
如果你编写一些getter方法,你可以很好地处理这个问题。Go的方法接收器只是普通的函数参数,所以在空接收器上调用某个方法是完全可以的:
type Foo struct {
    Name string
}
func (f *Foo) GetName() string {
    if f == nil {
        return "default name" // 或者是 "",随意
    }
    return f.Name
}
这个技巧在Go的protobuf实现中被使用。
英文:
You can handle this nicely if you code some getters. Go method receivers are just regular function arguments, so it's totally ok to call something on a nil receiver:
type Foo struct {
	Name string
}
func (f *Foo) GetName() string {
	if f == nil {
		return "default name" // or "", whatever
	}
	return f.Name
}
https://play.golang.org/p/Q20lSo65Kx
This trick is used e.g. by Go protobuf implementation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论