Golang,如何从func返回func? [英] Golang, how to return in func FROM another func?

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

问题描述

我想在调用/退出子func apiResponse()时在父func apiEndpoint() >

  func apiEndpoint(){
if false {
apiResponse(error)
//我希望apiResponse()调用返回(结束执行)在父func
//所以下一个apiResponse(all good)不会被执行
}

apiResponse (all good)
}

func apiResponse(消息字符串){
//通过JSON返回消息给用户
}


这就是说,它的责任是调用者结束执行并返回,显式地使用 return 语句。

如果示例与您的示例一样简单,可以通过使用 if-else 来避免 return 语句:

  func apiEndpoint(){
if someCondition {
apiResponse(error)
} else {
apiResponse(所有好的)
}
}

如果函数有返回值和 apiResponse()会返回一个值作为调用者的返回值,您可以执行 return 例如

  func apiEndpoint()int {
if someCondition {
return apiResponse(错误)
}

返回apiRes ponse(all good)
}

func apiResponse(消息字符串)int {
return 1 //返回一个int
}

注意: 但不是解决方案:如果被调用函数 panic(),则调用方函数中的执行将停止,并且调用顺序将在调用层级中上升(运行 defer 函数之后,并且它们不调用 recover())。恐慌恢复专为其他内容而设计,而不是被调用函数在调用函数中停止执行的意思。


I want to end execution in parent func apiEndpoint() upon calling/exiting in a child func 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.

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

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")
    }
}

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
}

Note:

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.

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

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