function - 在 Golang 中使用另一个函数返回一个值?

标签 function go error-handling

在 Go 中,是否可以仅使用函数返回?

例如,我想检查错误,而不是重复 if 语句,我只想调用一个函数,例如 checkErrors(err)

这是一个例子(goplayground)

func foobar(str string) err {
    _, err := ioutil.ReadAll(resp.Body)
    checkError(err) // If error != nil then foobar will return the err
    /*if err != nil {
        return err
    }*/
}

func checkError(err error) {
    if err != nil {
        // Then make the function this is being called within return the err.
    }
}

最佳答案

你的导师是对的:不要重复代码。它被称为 DRY principal .

但是 Go 的作者在设计这门语言时采取了不同的方向。它 split 了开发社区,引发了 war ,扭曲了空间和时间。

其中一个方向是接受一点点复制,以使代码更易于阅读。正如您所注意到的,错误处理就是这样一个领域。它会在您的应用程序中引入一种重复检查 nil 的模式,而不是抽象掉(并且很容易忽略)您应该做的真正的错误处理。

Rob Pike 在他的 GoLang 设计(和哲学)演讲中谈到了这个方向:

http://talks.golang.org/2012/splash.article

If errors use special control structures, error handling distorts the control flow for a program that handles errors. The Java-like style of try-catch-finally blocks interlaces multiple overlapping flows of control that interact in complex ways. Although in contrast Go makes it more verbose to check errors, the explicit design keeps the flow of control straightforward—literally.

不是每个人都同意,这就是 war 开始的原因。

但是,这些改变行业标准的决定给开发人员带来了如此多的负担,这正是他们这样做的原因:您每次都被迫预先和中心处理每个错误。您不能忽略或让其他东西处理它。

并非所有人都同意。

我强烈建议您和您的 Tutur 阅读那篇关于 Go 设计的文章。然后你们两个可以决定是否选择 Go 是 Go 的方式。

关于function - 在 Golang 中使用另一个函数返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36518018/

相关文章:

javascript - 不带参数的匿名函数返回带参数的自身

r - 函数对象的属性是什么/在哪里?

json - 如何计算结构或 JSON 文档中的属性数量?

exception - jqGrid 在创建定义时捕获异常

php - 尝试将函数的结果保存在 php 上

c - 我应该在 C 中声明系统调用函数吗?

去 XML 抑制自动生成的标签?

javascript - Client-Server 模型,使用 Dart 作为 Client,Go 语言作为 Server

php - 网址未显示错误/PHP

django - 在Django中使用try除外进行错误处理