英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论