douzhong1907 2017-11-15 21: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-15 21: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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部