douzhong1907 2017-11-16 05:10
浏览 203
已采纳

如何在golang中仅显示多值结果的一个输出

Recently, I studied that Golang can return multiple result for a function. So I write a function:

func store(x, y int) (int, int) {
    return x + y, x - y
}

After this I write the following code:

func main() {
    a, b := store(6, 4)
    fmt.Println(a, b)
} 

And, the result is:

10 2

This is working fine.

But if I want to print only a, then how can I do this?

func main() {
    a, b := store(6, 4)
    fmt.Println(a)
}

Result:

tmp/sandbox683412938/main.go:12:19: b declared and not used

Also, why I can't write:

func main() {
    a := store(6, 4) // ???
    fmt.Println(a)
}

Please, guide me.

  • 写回答

1条回答 默认 最新

  • duanjiu4498 2017-11-16 05:17
    关注

    You can use underscore placeholder (blank identifier) like this:

    a, _ := store(6, 4)
    fmt.Println(a)
    

    Output:

    10

    Here's the complete example:

    package main
    
    import (
        "fmt"
    )
    
    func store(x, y int) (int, int) {
        return x + y, x - y
    }
    
    func main() {
        a, _ := store(6, 4)
        fmt.Println(a)
    }
    

    Live example: https://play.golang.org/p/Z366BhtRA0

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

报告相同问题?

悬赏问题

  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上
  • ¥15 IPQ5018制作烧录固件,boot运行失败(操作系统-linux)(相关搜索:操作系统)(相关搜索:操作系统)