dongqiuqiu4736 2018-10-27 16:39
浏览 121
已采纳

fmt.Println()函数中的异常输出

I'm starting with golang (total noob), and I'm using a simple wrapper function for fmt.Println(str), just because it's shorter and I'm more used to it:

func echo(str ...interface{}) {
  fmt.Println(str)
}

The thing is that the output for echo("Hello") is [Hello] instead of Hello.

Am I missing some syntax detail here? How can I change the function to work as expected?

Besides the actual need for this function, I'm interested in the language-specific details about this issue.

Thanks!

  • 写回答

1条回答 默认 最新

  • doulangbi6869 2018-10-27 16:43
    关注

    The problem is that you send to fmt.Println parameter as a slice, but not as varadic.

    Change your method to :

    func echo(str ...interface{}) {
        fmt.Println(str...)
    }
    

    And it will work as you expect.

    Check topic Arguments to variadic functions from this site.

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

报告相同问题?

悬赏问题

  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具