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条)

报告相同问题?