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

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

calling golang println with variable arguments

问题

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

  1. var outputMax = 10
  2. var outputCnt = 0
  3. func output(args ...interface{}) {
  4. outputCnt++
  5. if outputCnt < outputMax {
  6. println(args)
  7. }
  8. }
  9. func main() {
  10. for i := 0; i < 5; i++ {
  11. output("Value of i is now:", i)
  12. }
  13. }

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

修复后的代码如下:

  1. package main
  2. import "fmt"
  3. var outputMax = 10
  4. var outputCnt = 0
  5. func output(args ...interface{}) {
  6. outputCnt++
  7. if outputCnt < outputMax {
  8. fmt.Println(args...)
  9. }
  10. }
  11. func main() {
  12. for i := 0; i < 5; i++ {
  13. output("Value of i is now:", i)
  14. }
  15. }

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

英文:

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 ?

  1. var outputMax = 10
  2. var outputCnt = 0
  3. func output(args ...interface{}) {
  4. outputCnt++
  5. if(outputCnt &lt; outputMax) { println(args) }
  6. }
  7. func main() {
  8. for i := 0; i &lt; 5; i++ {
  9. output(&quot;Value of i is now:&quot;, i)
  10. }
  11. }

答案1

得分: 4

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

  1. func output(args ...interface{}) {
  2. fmt.Println(args...)
  3. }

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

英文:

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

  1. func output(args ...interface{}) {
  2. println(args...)
  3. }

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:

确定