Making a printf-like function in Go

There are a lot of web answers for how to make printf style functions in Go, but several of them contain a similar annoying mistake where the output becomes malformatted. This example demonstrates the problem and the solution.

package main

import (
        "fmt"
)

func msg(format string, args ...any) {
        // This is what many web pages suggest is the correct thing to do,
        // but it results in garbage.
        fmt.Printf(format, args)
        // This is the correct way to do it so that you don't get square
        // brackets [] around the outputs.
        fmt.Printf(format, args...)
}

func main() {
        msg("hello %d %s\n", 10, "bonkers")
}

(download)

The output of the example looks like this:

hello [10 %!d(string=bonkers)] %!s(MISSING)
hello 10 bonkers

The important point to notice is that after args in the line fmt.Printf, you must add three dots, .... If you do as is suggested on many web pages, and don't add the dots, Go adds square brackets around your output.

See also Get a varargs-like vprintf or vfprintf in Go for a fuller example.


Copyright © Ben Bullock 2009-2026. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer