douchensou6495 2015-05-23 22:40
浏览 40
已采纳

如何区分具有多个返回值的函数的赋值和声明值?

When retrieving multiple returns from a function, I get that you can declare variables for the values on the fly by using := or assign the values to already existing variables by simply using =. My issue occurs when I want to assign one of the return values to an already existing variable while declaring a new variable for the other.

I have currently solved it by only assigning the values and declaring the required variables (bar in this case) beforehand, as in this snippet:

package main

import (
    "fmt"
)

func getFooAndBar() (foo string, bar string) {
    return "Foo", "Bar"
}

func main() {
    var foo = "default"
    var condition = true
    if condition {
        var bar string // Would like to avoid this step if possible
        foo, bar = getFooAndBar()
        fmt.Println(bar)
    }
    fmt.Println(foo)
}

If I use := it fails to build due to:

./app.go:16: foo declared and not used

So, is it possible to somehow avoid the step declaring bar separately?

  • 写回答

1条回答 默认 最新

  • doupeizheng3918 2015-05-24 01:12
    关注

    In this case you can't use the short variable declarations ":=" for redeclaring the foo variable, according to the spec:

    Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

    by eliminating ./app.go:16: foo declared and not used.

    func main() {
        var foo = "default"
        var condition = true
        if condition {
            foo, bar := getFooAndBar()
            fmt.Println(bar) // prints: Bar
            fmt.Println(foo) // prints: Foo
            // _ = foo
        }
        fmt.Println(foo) // prints: default
    }
    

    in this case foo is declared in the if block, this declaration will create a new variable shadowing the original foo variable in the outer block, the redeclaration of foo will happen only if you have declared foo and redeclared it with multi-variable short declaration within the same block.

    func main() {
        var foo = "default"     
        foo, bar := getFooAndBar()
        fmt.Println(bar) //prints: Bar
        fmt.Println(foo) //prints: Foo
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了