How to do method chaining for an interface?

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

How to do method chaining for an interface?

问题

我想要做类似于obj.WithX().WithY().WithZ()这样的操作。obj可以是不同的类型,这就是为什么我使用了一个接口。

不幸的是,obj也可能是nil。在这种情况下,我的方法链会引发恐慌,因为我在一个空接口上调用方法,而Go语言不知道要调用哪个方法。

minimal reproducible example here

如何在对象可能为nil的情况下仍然使用方法链?

  • 是否有一种方法可以为WithX()和其他函数提供默认实现?
  • 我还考虑过一种模式,其中每个属性函数都返回一个函数,但这似乎过于复杂。
obj.WithX().WithY()    // 类型为 func() myInterface
obj.WithX().WithY()()  // 现在我得到了实际的对象。
英文:

I would like to do something like obj.WithX().WithY().WithZ(). obj can have different types, which is why I am using an interface.

Unfortunately obj can also be nil. In that case my method chaining will panic, because I am calling a method on a nil-interface and go does not know which method to call.

minimal reproducible example here

How can I still use method-chaining with an object that may be nil?

  • Is there a way that I can provide a default implementation for WithX() and the other functions?
  • I also thought about a pattern where each of the property functions returns a function, but that seems overly complicated
obj.WithX().WithY()    // of type func() myInterface
obj.WithX().WithY()()  // now I got the actual object. 

答案1

得分: 1

这些评论大部分是正确的,但实际上你不能返回一个未指定类型的nil。

func new(someParam bool) inter {
    // 更复杂的情况。可能返回A、B或nil
    if someParam {
        return &A{}
    }
    var b *B
    return b // 它是nil,但是是实现了接口的类型
}

所以基本上你只需要一个“默认”类型,它可以是nil,但仍然实现了接口。

链接:https://go.dev/play/p/EE2k8VYJL9T

英文:

The comments are mostly correct, but really you just can't return an untyped nil.

func new(someParam bool) inter {
    // more complicated. May return A, B or nil
    if someParam {
	    return &A{}
    }
    var b *B
    return b // which is nil, but of a type that implements the interface
}

https://go.dev/play/p/EE2k8VYJL9T

So basically you just need a "default" type, which can be nil, which still implements the interface.

huangapple
  • 本文由 发表于 2023年3月8日 23:31:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75675048.html
匿名

发表评论

匿名网友

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

确定