Is it possible to define an optional receiver for a function?
func (r ReceiverType) doSth(arg ArgType) (ReturnType) {
if r == nil {
return doSthWithoutReceiver()
}
return r.doSthWithReceiver()
}
Such that I can call the function as follows:
var sth ReceiverType
resWithoutRecv := doSth()
resWithRecv := sth.doSth()
Without the need of basically writing the same function twice, once with and once without the receiver? Since I didn't find anything I assume this is bad practice either way?
It's not possible to make the receiver argument optional, but you can declare a method and a function with the same name:
func (r ReceiverType) doSth(arg ArgType) (ReturnType) {
return r.doSthWithReceiver()
}
func doSth(arg ArgType) (ReturnType) {
return doSthWithoutReceiver()
}
and call them as stated in the question:
var sth ReceiverType
resWithoutRecv := doSth()
resWithRecv := sth.doSth()
You can also check for a nil receiver:
func (r *ReceiverType) doSth(arg ArgType) (ReturnType) {
if r == nil {
return doSthWithoutReceiver()
}
return r.doSthWithReceiver()
}
and call it like this:
var sth *ReceiverType
resWithoutRecv := sth.doSth() // sth == nil