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
?
WithX()
and the other functions?obj.WithX().WithY() // of type func() myInterface
obj.WithX().WithY()() // now I got the actual object.
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.