Search code examples
govariadic-functions

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 ?


Solution

  • I would just do two prints:

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

    If you believed you needed to make a single call to Fprint, you could do,

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

    Either way seems simpler that building a new slice.