调用带有可变参数的 Golang 的 println 函数。

huangapple go评论67阅读模式
英文:

calling golang println with variable arguments

问题

我有以下代码用于调试目的打印n行。output()函数打印的是args的地址而不是参数。如何修复它?

var outputMax = 10
var outputCnt = 0

func output(args ...interface{}) {
    outputCnt++
    if outputCnt < outputMax {
        println(args)
    }
}

func main() {
    for i := 0; i < 5; i++ {
        output("Value of i is now:", i)
    }
}

我将为您提供修复后的代码。修复的方法是使用fmt.Println函数而不是println函数,并将args参数传递给fmt.Println函数。这样可以正确打印参数的值而不是地址。

修复后的代码如下:

package main

import "fmt"

var outputMax = 10
var outputCnt = 0

func output(args ...interface{}) {
    outputCnt++
    if outputCnt < outputMax {
        fmt.Println(args...)
    }
}

func main() {
    for i := 0; i < 5; i++ {
        output("Value of i is now:", i)
    }
}

请尝试运行修复后的代码,看看是否能正确打印参数的值。

英文:

I have the following code to print n lines for debug purposes. output() prints the address of args instead of the parameters. How to fix it ?

var outputMax = 10
var outputCnt = 0

func output(args ...interface{}) {
    outputCnt++
    if(outputCnt &lt; outputMax) { println(args) }
}

func main() {
    for i := 0; i &lt; 5; i++ {
        output(&quot;Value of i is now:&quot;, i)
    }
}

答案1

得分: 4

通常调用可变参数函数的方式如下:

func output(args ...interface{}) {
    fmt.Println(args...)
}

然而,这样会导致编译错误invalid use of ... with builtin println。如果改用fmt.Println(),应该就可以正常工作了。

英文:

The usual way to call a varargs function would be like so:

func output(args ...interface{}) {
    println(args...)
}

However, this will give you a invalid use of ... with builtin println compilation error. If you switch to fmt.Println() instead, it should work.

huangapple
  • 本文由 发表于 2013年12月3日 21:50:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/20352946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定