如何从另一个函数返回函数? [英] How to return in func FROM another func?

查看:21
本文介绍了如何从另一个函数返回函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在子函数 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.

话虽如此,调用者有责任结束执行并返回,明确地使用 return 语句.

That being said it is the responsibility of the caller to end the execution and return, explicitly with the return statement.

如果这个例子和你的一样简单,你可以通过使用 if-else 来避免 return 语句:

If the example is as simple as yours, you can avoid the return statement though by using if-else:

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

此外,如果函数具有返回值,并且 apiResponse() 将返回一个值,该值将是调用者的返回值,您可以在一个中执行 return行,例如

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 the return in one line, e.g.

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

    return apiResponse("all good")
}

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

注意:

仅出于完整性考虑,但不适用于您的情况:如果被调用函数会 panic(),则调用函数中的执行将停止,并且恐慌序列将在调用层次结构中上升(在运行 defer 函数后,如果它们不调用 recover()).恐慌恢复是为其他目的而设计的,而不是作为被调用函数停止调用函数执行的手段.

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 running defer functions, and if they don't call recover()). Panic-recover is designed for something else and not as a mean for callee functions to stop executions in caller functions.

这篇关于如何从另一个函数返回函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆