dongou3286 2018-09-22 16:46
浏览 35
已采纳

如何使用前缀参数更改fmt.Println的结果

I have the following code:

import "fmt"

func main() {
    P("1","2","3",0)
}

func P(prefix string,a ...interface{}){
    fmt.Println(prefix,a)
}

The result is:

1 [2 3 0]

But I would like to have one of the following results instead:

1 2 3 0
[1 2 3 0]

In other words: all arguments are of same importance, so no argument should be handled in a special way.

  • 写回答

2条回答 默认 最新

  • douna6802 2018-09-22 16:54
    关注

    Evgeny's solution (changing the function signature) is best, but if you can't change the function signature for whatever reason:

    func P(prefix string, a ...interface{}) {
        toPrint := []interface{}{prefix}
        toPrint = append(toPrint, a...)
        fmt.Println(toPrint...)  // 1 2 3 0
        // without the `...` you get [1 2 3 0]
    }
    

    Or you can just fmt.Printf in a loop:

    func P(prefix string, a ...interface{}) {
        fmt.Print(prefix)
        for _, aa := range a {
            fmt.Printf(" %v", aa)
        }
        fmt.Println()  // for your final newline
    }
    

    Of course the even better solution involves removing all doubt about the type you're passing in. interface{} means nothing -- define a type and stick with it!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?