dongyilai4214 2014-07-30 18:30
浏览 15
已采纳

在Go中记录多个返回值

Is there an idiomatic way to log result of a function returning multiple values? This won't compile:

import "log"
func returnPair() (int,int) {
    return 42, 24
}
func main() {
    log.Printf("Returned %v", returnPair())
}

prog.go:7: multiple-value returnPair() in single-value context

UPD summary (special thanks to @rvignacio):

This is a peculiarity in Go syntax:

func eat(args ...interface{}) {}

func eatWithSpice(spice string, args ...interface{}) {}

func main() {
    eat(returnPair()) // this works
    eatWithSpice("pepper", returnPair()) // this does not
}

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters. (http://golang.org/ref/spec#Calls)

  • 写回答

2条回答 默认 最新

  • doutinghou6980 2014-07-30 18:35
    关注

    You can assign those returning values first:

    a, b := returnPair()
    log.Printf("Returned %d %d", a, b
    

    You can see an example in "Multiple return values from Go functions".

    Using a multiple returning value directly in Println works though (since it accepts variadic parameters):

    In your case: <kbd>play.golang.org</kbd>

    package main
    
    import "log"
    
    func returnPair() (a int, b int) {
        return 42, 24
    }
    func main() {
        log.Println(returnPair())
    }
    

    Output:

    2009/11/10 23:00:00 42 24
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥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键失灵