Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap functions with "...interface{}" argument (like Printf)

Tags:

go

In my current project I am trying to write a logging function that will conditionally call fmt.Println.

My current Log function looks like this:

func Log(level int, a ...interface{}) {
    if level <= LogLevel {
        fmt.Println(a)
    }
}

But when I call it like this the output of Log gets encased in brackets for some reason:

http://play.golang.org/p/Aa8vC54Ih0

package main

import "fmt"

var LogLevel int

func main() {
    fmt.Println("string", 10, 3.1415926)
    LogLevel = 1
    Log(1, "string", 10, 3.1415926)
}

func Log(level int, a ...interface{}) {
    if level <= LogLevel {
        fmt.Println(a)
    }
}

string 10 3.1415926
[string 10 3.1415926]

This to me looks like the a argument in Log gets transformed somehow. How would I go about to pass a to fmt.Println in a way that is identical to calling fmt.Println directly?

like image 586
Splitlocked Avatar asked Jul 25 '13 13:07

Splitlocked


1 Answers

Just change fmt.Println(a) to fmt.Println(a...)

See "Passing arguments to ... parameters" in the go spec http://golang.org/ref/spec#Passing_arguments_to_..._parameters

like image 98
cthom06 Avatar answered Oct 22 '22 19:10

cthom06