英文:
Is it possible to "return" a function from another function?
问题
由于冗长的错误处理语法,我创建了一个名为check
的函数,作为一个“全局”错误处理程序。如果我想要抛出错误而不是记录日志,我只需要修改check
函数。问题是,现在我想要简单地return
,这样其他的Go协程在其中一个出现错误时仍然可以运行。所以问题是:我该如何做到这一点?是否可能?
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 {
return // 在这里返回而不是使用 log.Fatalf
}
}
然而,现在我发现如果有任何错误,我需要返回匿名函数而不是退出(使用log.Fatal
),所以我想知道是否可能返回匿名函数。
英文:
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
答案1
得分: 2
你可以让你的check函数返回一个bool值:
func checkIfFailed(errMsg string, err error) bool {
if err != nil {
log.Printf(errMsg, err)
return true
}
return false
}
这样,你仍然可以调用你的check函数(并在其中进行各种检查),同时可以从匿名函数中提前返回:
err = doSomething()
if checkIfFailed("this one failed", err) {
return
}
英文:
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
}
答案2
得分: 0
没有一种语言特性可以使父函数在简单函数调用的情况下自动返回。
但是,有一种方法可以导致当前 goroutine 退出,这可能是你想要的:runtime.Goexit
。请注意,这与调用 os.Exit
具有类似的破坏性潜力,因此在由其他包或其他不相关代码创建的 goroutine 上调用它将是不好的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论