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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵