I want to end execution in parent func apiEndpoint()
upon calling/exiting in a child func apiResponse()
func apiEndpoint() {
if false {
apiResponse("error")
// I want apiResponse() call to return (end execution) in parent func
// so next apiResponse("all good") wont be executed
}
apiResponse("all good")
}
func apiResponse(message string) {
// returns message to user via JSON
}
A function or method cannot control the execution (control flow) from where it was called from. You don't even have guarantee it was called from your function, it may be called to initialize a global variable for example.
That being said it is the responsibility of the caller to end the execution and return, explicitly with the
return
statement.If the example is as simple as yours, you can avoid the
return
statement though by usingif-else
:Also if the functions have return values and the
apiResponse()
would return a value that would be the return value of the caller, you can do thereturn
in one line, e.g.Note:
Just for completeness but not as a solution in your case: if the callee function would
panic()
, the execution in the caller function would stop and the panicing sequence would go up in the call hierarchy (after runningdefer
functions, and if they don't callrecover()
). Panic-recover is designed for something else and not as a mean for callee functions to stop executions in caller functions.