Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending items to a variadic function wrapper without reallocating a new slice

Ok I need a small wrapper of fmt.Printf() for debugging conveniance :

1/ "too many arguments in call to fmt.Fprintln" :

func Debug (a ... interface{}) {
    if debug {
        fmt.Fprintln(out, prefix, sep, a...)
    }
}

2/ "name list not allowed in interface type" :

func Debug (a ... interface{}) {
    if debug {
        fmt.Fprintln(out, []interface{prefix, sep, a...}...)
    }
}

3/ Works, but feels wrong :

func Debug (a ... interface{}) {
    if debug {
        sl := make ([]interface{}, len(a) + 2)
        sl[0] = prefix
        sl[1] = sep
        for i, v := range a {
            sl[2+i] = v
        }

        fmt.Fprintln(out, sl...)
    }
}

Any ideas to avoid allocating extra memory ?

like image 214
r---------k Avatar asked Dec 22 '11 14:12

r---------k


1 Answers

You can also use append for a one-liner:

func Debug (a ...interface{}) {
    if debug {
        fmt.Fprintln(out, append([]interface{}{prefix, sep}, a...}...)
    }
}
like image 197
sebastian Avatar answered Sep 23 '22 23:09

sebastian