Go Package fmt: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(44 intermediate revisions by the same user not shown)
Line 5: Line 5:
=Internal=
=Internal=
* [[Go_Language_Modularization#fmt|Standard Library]]
* [[Go_Language_Modularization#fmt|Standard Library]]
* [[Go_Strings#String_Manipulation_and_Processing_in_Go|String Manipulation and Processing in Go]]
=Formatting=
=Formatting=
A format string, or a template, is text interspersed with [[#Conversion_Characters|conversion characters]].
==Conversion Characters==
The conversion characters are also known as '''placeholders'''.
===<tt>%v</tt>===
Render the value as string in the default format. It is a catch-all placeholder, "v" stands for "value". It can be used to print any value, including arrays, slices, structs and maps. For maps, the Printf functions sort the output lexicographically by key.
"%v" and <code>fmt.Errorf()</code> is typically used in the error handling idiom that involves [[Go_Language_Error_Handling#Annotate_the_Error|error annotation]].
===<tt>%+v</tt>===
When printing structs, the plus flag <code>%+v</code> adds field names.
===<tt>%#v</tt>===
A Go-syntax representation of the value.
<code>%#v</code> can be used to show that an <code>error</code> instance returned by <code>errors.New("something")</code> is a pointer:
<font size=-2>
&errors.errorString{s:"something"}
</font>
===<tt>%T</tt>===
A Go-syntax representation of the type of the value.
===<tt>%%</tt>===
A literal percent sign. Consumes no value.
===Strings===
====<tt>%s</tt>====
<syntaxhighlight lang='go'>
color := "blue"
fmt.Printf("The color is %s\n", color)
</syntaxhighlight>
====<tt>%q</tt>====
Prints a double-quoted string safely escaped with Go syntax. When applied to <code>string</code> and <code>[]byte</code>, it double-quotes. When applied to integers and runes, producing a single-quote rune constant.
The <code>%#q</code> use backquotes instead if possible.
===Integers===
<syntaxhighlight lang='go'>
size := 1
fmt.Printf("The size is %d\n", size)
</syntaxhighlight>
====<tt>%q</tt>====
Prints a a single-quoted character literal, which is the interpretation of the given int, safely escaped with Go syntax.
<syntaxhighlight lang='go'>
c := 10
fmt.Printf("%q", c)
</syntaxhighlight>
will print:
<syntaxhighlight lang='text'>
'\n'
</syntaxhighlight>
===Characters===
<syntaxhighlight lang='go'>
c := 'x'
fmt.Printf("The character is %c\n", c)
</syntaxhighlight>
===Booleans===
<syntaxhighlight lang='go'>
b := true
fmt.Printf("The boolean value is %t\n", b)
</syntaxhighlight>
===Floating Point Numbers===
====<tt>%b</tt>====
Decimalless scientific notation with exponent a power of two, in the manner of strconv.FormatFloat with the 'b' format, e.g. -123456p-78
====<tt>%e</tt>====
Scientific notation, e.g. -1.234456e+78
====<tt>%E</tt>====
Scientific notation, e.g. -1.234456E+78
====<tt>%f</tt>====
Decimal point but no exponent, e.g. 123.456


==Leading Zero Padding for Integers==
<syntaxhighlight lang='go'>
f := 1.0
fmt.Printf("The floating point value is %f\n", f)
</syntaxhighlight>
 
Limit the number of decimals:
<syntaxhighlight lang='go'>
fmt.Printf("The floating point value is %.2f\n", f)
</syntaxhighlight>
 
If the number of decimals comes as a variable, see [[#Numerical_Value_part_of_the_Conversion_Character_as_Argument_of_the_Function|Numerical Value Part of the Conversion Character as Argument of the Function]] below.
 
====<tt>%F</tt>====
Synonym for %f.
====<tt>%g</tt>====
%e for large exponents, %f otherwise.
====<tt>%G</tt>====
%E for large exponents, %F otherwise
====<tt>%x</tt>====
Hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20
 
Works on strings, byte arrays and byte slices, as well as on integers. Generates a long hexadecimal string.
 
<code>% x</code> with a space in the format puts a space between the bytes.
 
====<tt>%X</tt>====
Upper-case hexadecimal notation, e.g. -0X1.23ABCP+20
 
===<tt>%w</tt>===
Used with <code>fmt.Errorf()</code> to [[Go_Language_Error_Handling#Wrap_the_Error_Instance|wrap errors]].
 
==Pointers==
{{Internal|Pointers_in_Go#Displaying_Pointers|Pointers in Go &#124; Displaying Pointers}}
 
==Structs==
{{Internal|Go_Structs#Printing_Structs|Go Structs &#124; Printing Structs}}
 
==Padding==
===Leading Zero Padding for Integers===
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
i := 7
i := 7
s := fmt.Sprintf("%06d", i) // will produce "000007" (five zeroes)
s := fmt.Sprintf("%06d", i) // will produce 000007 (five zeroes)
</syntaxhighlight>
</syntaxhighlight>
If the number of padding characters comes as a variable, see [[#Numerical_Value_part_of_the_Conversion_Character_as_Argument_of_the_Function|Numerical Value Part of the Conversion Character as Argument of the Function]] below.


==Leading Space Padding for Integer==
===Leading Space Padding for Integer===
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
i := 7
i := 7
s := fmt.Sprintf("%6d", i) // will produce "     7" (five spaces)
s := fmt.Sprintf("%6d", i) // will produce '     7' (five spaces)
</syntaxhighlight>
</syntaxhighlight>
If the number of padding characters comes as a variable, see [[#Numerical_Value_part_of_the_Conversion_Character_as_Argument_of_the_Function|Numerical Value Part of the Conversion Character as Argument of the Function]] below.


==<tt>%v</tt>==
===String Padding===
Print the value in the default format.
Left:
<syntaxhighlight lang='go'>
fmt.Sprintf("%10s", "test")
</syntaxhighlight>
Right:
<syntaxhighlight lang='go'>
fmt.Sprintf("%-10s", "test")
</syntaxhighlight>
Padding quantity specified as parameter of the function (also see [[#Numerical_Value_part_of_the_Conversion_Character_as_Argument_of_the_Function|Numerical Value Part of the Conversion Character as Argument of the Function]] below):
<syntaxhighlight lang='go'>
fmt.Sprintf("%*s", 10, "test")
</syntaxhighlight>


==<tt>%+v</tt>==
==Numerical Value part of the Conversion Character as Argument of the Function==
When printing structs, the plus flag <code>%+v</code> adds field names.
If the number of padding characters or other configurable value in a conversion character is variable, the following <code>*</code> syntax can be used:
<syntaxhighlight lang='go'>
zeroPaddingCount := 4
i := 1
fmt.Printf("%0*d", zeroPaddingCount, i) // will print 0001
</syntaxhighlight>
 
If the value passed as 'zeroPaddingCount' is 0, no padding is done.
 
To pad a string to the left with a configurable number of spaces:
<syntaxhighlight lang='go'>
depth := 5
fmt.Printf("%*s\n", depth, ".")
</syntaxhighlight>


=Functions=
=Functions=
Line 40: Line 173:


==<tt><span id='fmt.Errorf.28.29'></span>Errorf()</tt>==
==<tt><span id='fmt.Errorf.28.29'></span>Errorf()</tt>==
{{Internal|Go_Language_Error_Handling#Wrapping_Errors|Error Handling &#124; Wrapping Errors}}
{{Internal|Go_Language_Error_Handling#fmt.Errorf.28.29|Go Language Error Handling}}
=Interfaces=
==<tt>Fprintf()</tt>==
==<tt>fmt.Stringer</tt>==
The <code>Fprintf()</code> function can be used to print to <code>stderr</code>.
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
type Stringer interface {
if cnt, err := fmt.Fprintf(os.Stderr, "%s\n", "something"); err != nil {
  String() string
panic(err)
} else {
  ...
}
}
</syntaxhighlight>
</syntaxhighlight>
<code>Stringer</code> is implemented by any type that has a <code>String()</code> method, which defines the "native" format for that value. The <code>String()</code> method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as <code>Print</code>. For a usage example, see: {{Internal|The Equivalent of Java toString() in Go#Overview|The Equivalent of Java toString() in Go}}
 
=Interfaces=
==<tt>fmt.Stringer</tt>==
See {{Internal|Go_String()#Overview|<tt>String()</tt>}}

Latest revision as of 05:00, 3 November 2024

External

Internal

Formatting

A format string, or a template, is text interspersed with conversion characters.

Conversion Characters

The conversion characters are also known as placeholders.

%v

Render the value as string in the default format. It is a catch-all placeholder, "v" stands for "value". It can be used to print any value, including arrays, slices, structs and maps. For maps, the Printf functions sort the output lexicographically by key.

"%v" and fmt.Errorf() is typically used in the error handling idiom that involves error annotation.

%+v

When printing structs, the plus flag %+v adds field names.

%#v

A Go-syntax representation of the value.

%#v can be used to show that an error instance returned by errors.New("something") is a pointer:

&errors.errorString{s:"something"}

%T

A Go-syntax representation of the type of the value.

%%

A literal percent sign. Consumes no value.

Strings

%s

color := "blue"
fmt.Printf("The color is %s\n", color)

%q

Prints a double-quoted string safely escaped with Go syntax. When applied to string and []byte, it double-quotes. When applied to integers and runes, producing a single-quote rune constant.

The %#q use backquotes instead if possible.

Integers

size := 1
fmt.Printf("The size is %d\n", size)

%q

Prints a a single-quoted character literal, which is the interpretation of the given int, safely escaped with Go syntax.

c := 10
fmt.Printf("%q", c)

will print:

'\n'

Characters

c := 'x'
fmt.Printf("The character is %c\n", c)

Booleans

b := true
fmt.Printf("The boolean value is %t\n", b)

Floating Point Numbers

%b

Decimalless scientific notation with exponent a power of two, in the manner of strconv.FormatFloat with the 'b' format, e.g. -123456p-78

%e

Scientific notation, e.g. -1.234456e+78

%E

Scientific notation, e.g. -1.234456E+78

%f

Decimal point but no exponent, e.g. 123.456

f := 1.0
fmt.Printf("The floating point value is %f\n", f)

Limit the number of decimals:

fmt.Printf("The floating point value is %.2f\n", f)

If the number of decimals comes as a variable, see Numerical Value Part of the Conversion Character as Argument of the Function below.

%F

Synonym for %f.

%g

%e for large exponents, %f otherwise.

%G

%E for large exponents, %F otherwise

%x

Hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20

Works on strings, byte arrays and byte slices, as well as on integers. Generates a long hexadecimal string.

% x with a space in the format puts a space between the bytes.

%X

Upper-case hexadecimal notation, e.g. -0X1.23ABCP+20

%w

Used with fmt.Errorf() to wrap errors.

Pointers

Pointers in Go | Displaying Pointers

Structs

Go Structs | Printing Structs

Padding

Leading Zero Padding for Integers

i := 7
s := fmt.Sprintf("%06d", i) // will produce 000007 (five zeroes)

If the number of padding characters comes as a variable, see Numerical Value Part of the Conversion Character as Argument of the Function below.

Leading Space Padding for Integer

i := 7
s := fmt.Sprintf("%6d", i) // will produce '     7' (five spaces)

If the number of padding characters comes as a variable, see Numerical Value Part of the Conversion Character as Argument of the Function below.

String Padding

Left:

fmt.Sprintf("%10s", "test")

Right:

fmt.Sprintf("%-10s", "test")

Padding quantity specified as parameter of the function (also see Numerical Value Part of the Conversion Character as Argument of the Function below):

fmt.Sprintf("%*s", 10, "test")

Numerical Value part of the Conversion Character as Argument of the Function

If the number of padding characters or other configurable value in a conversion character is variable, the following * syntax can be used:

zeroPaddingCount := 4
i := 1
fmt.Printf("%0*d", zeroPaddingCount, i) // will print 0001

If the value passed as 'zeroPaddingCount' is 0, no padding is done.

To pad a string to the left with a configurable number of spaces:

depth := 5
fmt.Printf("%*s\n", depth, ".")

Functions

Sprintf()

Format a string and returns it as a result:

message := fmt.Sprintf("Hi, %v. Welcome!", name)

For more details on the format string, see:

Printf() Format String

Printf(), Println()

Printing to stdout and stderr

Scanf(), Scanln()

Handling stdin in Go

Errorf()

Go Language Error Handling

Fprintf()

The Fprintf() function can be used to print to stderr.

if cnt, err := fmt.Fprintf(os.Stderr, "%s\n", "something"); err != nil {
	panic(err)
} else {
  ...
}

Interfaces

fmt.Stringer

See

String()