Home >Backend Development >Golang >How Can I Return from a Parent Function in Go After a Child Function Executes?

How Can I Return from a Parent Function in Go After a Child Function Executes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 00:39:02243browse

How Can I Return from a Parent Function in Go After a Child Function Executes?

Returning from a Child Function within a Parent Function

One may encounter a situation where they wish to return from a parent function upon calling a child function. In this scenario, the goal is to terminate execution in the parent function apiEndpoint() when a certain condition is met in the child function apiResponse().

The Issue

Using the provided code snippet:

func apiEndpoint() {
    if false {
        apiResponse("error")
        // Return execution in parent function
        // Skip execution of apiResponse("all good")
    }

    apiResponse("all good")
}

func apiResponse(message string) {
    // Returns message to user via JSON
}

The intent is to have apiResponse("error") terminate the execution of apiEndpoint() so that apiResponse("all good") is not executed. However, the default behavior in Go is that a function cannot control execution flow outside of its scope.

Resolution

To achieve the desired outcome, there are several approaches:

1. Use if-Else Statements

If the condition is simple enough, the if-else structure can be used to avoid the explicit return statement:

func apiEndpoint() {
    if someCondition {
        apiResponse("error")
    } else {
        apiResponse("all good")
    }
}

2. Return from Caller Using Values

If both functions return values, you can use a single line of code to return the appropriate value from the caller function:

func apiEndpoint() int {
    if someCondition {
        return apiResponse("error")
    }

    return apiResponse("all good")
}

func apiResponse(message string) int {
    return 1 // Return an int
}

Note

While panicing is another exception that can halt execution, it is not considered a suitable solution in this context and should be reserved for exceptional situations.

The above is the detailed content of How Can I Return from a Parent Function in Go After a Child Function Executes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn