在链式调用中传播变量的“nilness”是否有方法?

huangapple go评论154阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年5月23日 04:57:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/44122034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定