duandi8838 2017-11-05 14:57
浏览 19
已采纳

命名返回变量未设置为for循环

I have a GoLang function that tries to set some named return variables inside a FOR loop. It looks something like this:

func (dbs *myClient) DoStuff() (response []byte, e error) {
    for i:=0;i<5;i+=1 {
        response, e = dbs.doNetworkThing()
        if e == nil {
            break;
        }
    }
    return response, e
}

Basically what I'd like to do is set the return variables response and e to first result from doNetworkThing() that does not fail.

The problem is that response and e get reset once I exit from the for loop. What's the correct idiomatic way of doing something like this in GoLang?

I really want to use named return variables since they make things easier to read (I would consider something like this to be an ugly solution).

// Seems to be an ugly solution - would prefer using named return vars
func (dbs *myClient) DoStuff() ([]byte, error) {
    var response []byte
    var e error
    for i:=0;i<5;i+=1 {
        response, e := dbs.doNetworkThing()
        if e == nil {
            break;
        }
    }
    return response, e
}
  • 写回答

2条回答 默认 最新

  • doutan5844 2017-11-05 15:17
    关注

    The code below seems to work (compiles). tested here.

    func (dbs *myClient) DoStuff() (response []byte, e error) {
        for i:=0;i<5;i+=1 {
            response, e = dbs.doNetworkThing()
            if e == nil {
                break;
            }
        }
        return
    }
    

    What I did:

    1. I removed the response and e declaration as it is already declared the moment you named your return values.
    2. changed := to = because (again) the variable is already declared
    3. changed return response, e to return since the return values are named

    Hope it helps! :)

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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端