Search code examples
goprintln

How to change the result of fmt.Println with a prefix argument


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.


Solution

  • 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!