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.
|
|
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.