drdawt9210 2019-07-19 17:03
浏览 55
已采纳

命名来自多重返回函数的接收变量

Go allows for multiple named return values, but what about the receiving variables? Are they protected when return values are juggled around?

Let's say we start with this:

func foo() (i int, j int) {
   i = 1
   j = 2
   return
}

a, b := foo()

Now what if some other coder comes by and makes the following change to foo's definition:

func foo() (j int, i int) {

my calling function is invalidated. Is it, then, possible to name the returned values from the calling side as well. For instance, if I called it like this:

(a:i, b:j) := foo()

then I would be attaching them to the named return values, rather than assigning them in the order they are returned.

So, is there a way to solve that problem?

  • 写回答

1条回答 默认 最新

  • dongzhanlu0658 2019-07-19 17:15
    关注

    This is no different than rearranging the input parameters. As a rule, don't do that unless you intend to make a breaking change. But if you want to deal with things by name rather than position, you want a struct. For example, you can use anonymous structs:

    func foo() struct {
        i int
        j int
    } {
        return struct {
            i int
            j int
        }{1, 2}
    }
    
    func main() {
        result := foo()
        fmt.Println(result.i, result.j)
    }
    

    Of course you can also name the struct if you used it in other places, but there's no need if you just want to name the fields.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能