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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程