Skip to main content
  1. 2024/
  2. Posts from April/

Golang and Hugo printf tokens

Making it a bit easier to get thoughts out™️.

I found a useful site1 which outlined some of the tokens/verbs supported by go’s fmt tool…:

(IOW: what does the character after the % mean to golang’s printf / fmt library?)

%v
formats the value in a default format
%t
formats true or false values
%s
formats string values
%d
formats decimal integers
%g
formats the floating-point numbers
%b
formats base 2 numbers
%o
formats base 8 numbers

However, that site didn’t list all of the options2

The formatting ‘verbs’ are derived from C’s but are simpler.

The Verbs: #

Self-descriptive Verbs #
Numerical Verbs #
String and Slice Verbs #

General: #

`%v
The value in a default format when printing structs.
The inclusion of the plus flag: (%+v) adds field names
%#v
A Go-syntax representation of the value
%T
A Go-syntax representation of the type of the value
%%
A literal percent sign; consumes no value

Boolean: #

%t
the word true or false

Numerical #

Integer: #

%b
base 2
%c
the character represented by the corresponding Unicode code point
%d
base 10
%o
base 8
%O
base 8 with 0o prefix
%q
a single-quoted character literal safely escaped with Go syntax.
%x
base 16, with lower-case letters for a-f
%X
base 16, with upper-case letters for A-F
%U
Unicode format: U+1234; same as “U+%04X

Floating-point and complex constituents: #

%b
Decimal-less scientific notation with exponent a power of two, in the manner of strconv.FormatFloat with the ‘b’ format.
Example: -123456p-78
%e
Scientific notation.
Example: -1.234456e+78
%E
Scientific notation.
Example: -1.234456E+78
%f
Decimal point but no exponent.
Example: 123.456
%F
Synonym for %f
%g
%e For large exponents, %f otherwise.
Precision is discussed below.
%G
%E for large exponents, %F otherwise.
Precision is discussed below.
%x
Hexadecimal notation
(with decimal power of two exponent).
Example: -0x1.23abcp+20
%X
Upper-case hexadecimal notation.
Example: -0X1.23ABCP+20

Strings and Slices (of bytes) #

(treated equivalently by these verbs):

String: #
%s
The uninterpreted bytes of the string or slice
%q
A double-quoted string safely escaped with Go syntax
%x
base 16, lower-case, two characters per byte
%X
base 16, upper-case, two characters per byte
Slice: #
%p
Address of 0th element in base 16 notation, with leading 0x
Pointer: #
%p
Base 16 notation, with leading 0x
The %b, %d, %o, %x, and %X verbs also work with pointers.
Formatting the value exactly as if it were an integer.

Defaults #

The default format for %v is

bool %t
int int8 etc. %d
uint uint8 etc.
%d
(if printed with %#v) %#x
float32 complex64 etc %g
string %s
chan %p
pointer %p

Precision #

For compound objects, the elements are printed using these rules, recursively, laid out like this:

Width is specified by an optional decimal number immediately preceding the verb.
If absent, the width is whatever is necessary to represent the value.

Precision is specified after the (optional) width by a period followed by a decimal number.
If no period is present, a default precision is used.
A period with no following number specifies a precision of zero.

Examples #

struct {field0 field1 ...}
array, slice [elem0 elem1 ...]
maps, map[k1:v1 k2:v2 ...]
pointer to above &{}, &[], &map[]
verb width precision
%f default default
%9f 9 default
%.2f default 2
%9.2f 9 2
%9.f 9 0

Width and precision are measured in units of Unicode code points, that is, runes.3

Either or both of the flags may be replaced with the character ‘*’, causing their values to be obtained from the next operand (preceding the one to format), which must be of type int.

For most values, width is the minimum number of runes to output, padding the formatted form with spaces if necessary.

For strings, byte slices and byte arrays, however, precision limits the length of the input to be formatted (not the size of the output), truncating if necessary.
Precision is normally is measured in runes. For these type, however, when formatted with the %x or %X format it is measured in bytes.

For floating-point values, width sets the minimum width of the field and precision sets the number of places after the decimal, if appropriate.
Except for %g/%G wherein precision sets the maximum number of significant digits
(trailing zeros are removed).

Examples #

Input Format Output
12.345 %6.3f 12.345
12.345 %.3g 12.3

The default precision for %e, %f and %#g is 6;

For %g it is the smallest number of digits necessary to identify the value uniquely.

For complex numbers, the width and precision apply to the two components independently
and the result is parenthesized, so %f applied to 1.2+3.4i
produces (1.200000+3.400000i).

When formatting a single integer code point or a rune string (type []rune) with %q,
invalid Unicode code points are changed to the Unicode replacement character, U+FFFD, as in strconv.QuoteRune.

Other flags: #

#’ Alternate format:
  • Add leading 0b for binary (%#b)
  • Add leading 0 for octal (%#o)
  • Add leading 0x, 0X for hex (%#x or %#X)
  • Suppress 0x for %p (%#p)
  • For %q, if strconv.CanBackquote returns true print a raw (backquoted) string.
  • Always print a decimal point for %e, %E, %f, %F, %g and %G
  • Do not remove trailing zeros for %g and %G
  • Write e.g. U+0078x’ if the character is printable for %U (%#U).

Flags are ignored by verbs that do not expect them.
For example there is no alternate decimal format, so %#d and %d behave identically.

+
Always print a sign for numeric values. Guarantee ASCII-only output for %q (%+q)
-
Pad with spaces on the right rather than the left
(left-justify the field)
’ (space)
  • Leave a space for elided sign in numbers (% d).
  • Put spaces between bytes printing strings or slices in hex (% x, % X)
0
  • Pad with leading zeros rather than spaces.
  • For numbers, this moves the padding after the sign.
  • Ignored for strings, byte slices and byte arrays

Printf-Like operands #

For each Printf-like function, there is also a Print function

  • Takes no format
  • Is equivalent to passing %v for every operand.

Another variant Println

  • Inserts blanks between operands and appends a newline.

Regardless of the verb, if an operand is an interface value, the internal concrete value is used, not the interface itself.

Thus (UNLESS printed using the verbs %T and %p):

var i interface{} = 23
fmt.Printf("%v\n", i)

will emit 23.

Exceptions #

Special formatting considerations apply for operands that implement certain interfaces.

In order of application:

  1. If the operand is a reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.

  2. If an operand implements the Formatter interface, it will be invoked. In this case the interpretation of verbs and flags is controlled by that implementation.

  3. If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.

If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %x %X), or is %v but not %#v, the following two rules apply:

  1. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

  2. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

For compound operands such as slices and structs, the format applies recursively to the elements of each operand, not to the operand as a whole.
Thus %q will quote each element of a slice of strings, and %6.2f will control formatting for each element of a floating-point array.

However, when printing a byte slice with a string-like verb (%s %q %x %X), it is treated identically to a string, as a single item.


  1. https://www.educative.io/answers/how-to-use-the-printf-function-in-golang ↩︎

  2. https://pkg.go.dev/fmt ↩︎

  3. (This differs from C’s printf where the units are always measured in bytes.) ↩︎