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

Mary-Kate Olsen
Release: 2024-11-16 00:39:02
Original
148 people have browsed it

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
}
Copy after login

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")
    }
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template