如何从另一个func返回func?

我想apiEndpoint()在调用/退出子函数时结束父函数的执行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

}


江户川乱折腾
浏览 290回答 2
2回答

元芳怎么了

函数或方法无法从调用它的地方控制执行(控制流)。你甚至不能保证它是从你的函数中调用的,例如,它可能被调用来初始化一个全局变量。话虽如此,调用者有责任用return语句明确地结束执行并返回。如果示例和您的一样简单,您可以return使用if-else以下语句来避免该语句:func apiEndpoint() {    if someCondition {        apiResponse("error")    } else {        apiResponse("all good")    }}此外,如果函数具有返回值并且apiResponse()将返回一个值作为调用者的返回值,您可以return在一行中执行,例如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()) . 恐慌恢复是为其他目的而设计的,而不是作为被调用函数停止调用函数执行的一种手段。

暮色呼如

使用return语句:func apiEndpoint() {    if false {        apiResponse("error")        return    }    apiResponse("all good")}func apiResponse(message string) {    // returns message to user via JSON}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go