Print the Go syntax representation of a value

February 15, 2024

I learned a new trick: fmt.Sprintf (and fmt.Printf) support a format verb %#v that prints out a “Go-syntax representation of the value” (quoting the documentation).

What this mean: you can ouput a value the way you would write it in valid Go source code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import "fmt"

func main() {

	var s = []string{"string in the slice"}

	fmt.Printf("%v\n", s) // output: [string in the slice]
	fmt.Printf("%#v\n", s) // output: []string{"string in the slice"}
	// To output only the type, you can use `%T` instead
	fmt.Printf("%T\n", s) // output: []string
}

Why is it useful?

For me it was useful when using Go template to generate Go code (generating CLI commands from OpenAPI specification).

In my input file, I had a slice I wanted to insert into the generated code, but I can’t use the value directly, because it’s not valid Go code. There is a few workaround (like iterating on the slice to output each value inside and reconstructing the slice) but using %#v is by far the best approach.

References

If you have questions, suggestions or want to discuss about this subject, I'd be more than happy if you reach me at conta-remove-ct@julienrouse.com. See also my open invite
Nifty tech tag lists from Wouter Beeftink