How to do method chaining for an interface?

83 Views Asked by At

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

There are 1 best solutions below

1
dave On BEST ANSWER

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.