dskzap8756 2016-04-09 14:21
浏览 380
已采纳

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

In Go, is it possible to return using a function only?

For example, I want to check for errors and instead of repeating an if statement, I want to just call a function such as checkErrors(err).

Here is an example (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.
    }
}
  • 写回答

2条回答 默认 最新

  • duanpei8853 2016-04-09 14:52
    关注

    Your tutor is correct: don't repeat code. It is called the DRY principal.

    But the authors of Go have taken a different direction when designing the language. And it has fractured the development community, it has caused wars, it has warped space and time.

    One of these directions is to accept a little bit of copying, to make the code easier to read. Error handling, as you have noticed, is one such area. It invites a little repetitous pattern of checking for nil all over your app instead of abstracting away (and easily able to ignore) the true error handling you should be doing.

    Rob Pike addressed this direction in his Design (and Philosophy) of GoLang talk:

    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.

    Not everyone agrees and it's why wars are started.

    But, these decisions to shake up the industry standards that has put so much if a burden on developers is exactly why they are doing it: you are forced to deal with each error up front and center, every time. You cannot ignore or let something else handle it.

    Not everyone agrees.

    I highly suggestion you and your Tutur read that post about the design of Go. Then you two can make the decision of rather Go is the way to Go or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵