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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料