Reputation: 2022
I want to create a function that will work exactly like fmt.Printf
but also left pad the string with current timestamp. Ideally I would like to override printf and println to do this job, but the first solution is also ok.
This is what I've done:
func output(message string, a ...interface{}) {
fmt.Printf(getCurrentTime() + " " + message, a)
}
func getCurrentTime() string {
t := time.Now()
return t.Format("[2006-01-02 15:04:05]")
}
But it outputs strange results when I pass variables.
How should I do this?
Upvotes: 0
Views: 923
Reputation: 12246
If you want to pass variadic elements from a function to another, you have to expand them. From your example, a
is an []interface
, so you are passing only two arguments to the actual fmt.Printf
: the message and an array.
You have to correct the call:
fmt.Printf(getCurrentTime() + " " + message, a...)
A little example to show what happens:
func exec(args ...interface{}) {
fmt.Println(args)
}
func insert(args ...interface{}) {
exec(args) // Prints [[5 42]]
exec(args...) // Prints [5 42]
}
func main() {
insert(5, "42")
}
Upvotes: 3