Get a varargs-like vprintf or vfprintf in Go
This page was created on Mon Sep 28 2015 and last changed on Sat Oct 05 2024.
This is an example Go program demonstrating how to get a "varargs"
effect like vprintf
or vfprintf
in C. The
trick is to declare your "varargs" as ...interface{}
then
send them on to the next function as a...
. This example
demonstrates printing an error message with the file name and line
number.
package main import ( "fmt" "os" "runtime" ) func line_err(format string, a ...any) { _, file, line, _ := runtime.Caller(1) fmt.Fprintf(os.Stderr, "%s:%d: ", file, line) fmt.Fprintf(os.Stderr, format, a...) fmt.Fprintf(os.Stderr, "\n") } func main() { line_err("Try %d this %s out", 1, "moo") }
The output of the example looks like this:
/share/websites/www.lemoda.net/go/varargs/v.go:17: Try 1 this moo out
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer