hey
hey

Reputation: 7819

Is it possible to "return" a function from another function?

Due the verbose error handling syntax I've created a function check as below which acts as a "global" error handler. If I want to panic instead to log I change only the check function. The issue is that now I want to simply return so that the other go routines can still run if one has an error. So the question is: How can I do that ? Is it possible?

func main() {
    for k, v := range foo {
        go func() {
            err = doSomething()
            check("this one failed", err)
        }()
    }
}

func check(errMsg string, err error) {
    if err != nil {
        log.Fatalf(errMsg, err)
    }
}

However now I've found that I need return the anonymous function if there is any error rather than exit ( log.Fatal ) so I'm wondering if it's possible to return the anyonymou

Upvotes: 2

Views: 135

Answers (2)

James Henstridge
James Henstridge

Reputation: 43899

There isn't a language feature that allows you to cause the parent function to automatically return in response to a simple function call.

However, there is a way to cause the current goroutine to exit, which might be what you are after: runtime.Goexit. Note that this has similar disruptive potential to calling os.Exit, so it would be bad to call it in the context of goroutines created by other packages or other unrelated code.

Upvotes: 0

VonC
VonC

Reputation: 1323203

You could make your check function returns a bool:

func checkIfFailed(errMsg string, err error) bool {
    if err != nil {
        log.Printf(errMsg, err)
        return true
    }
    return false
}

That way, you can still call your check (and do all kind of checks in it), while returning early from the anonymous function:

err = doSomething()
if checkIfFailed("this one failed", err) {
    return
}

Upvotes: 2

Related Questions