Go Package fmt: Difference between revisions
Jump to navigation
Jump to search
(→%+v) |
|||
Line 6: | Line 6: | ||
* [[Go_Language_Modularization#fmt|Standard Library]] | * [[Go_Language_Modularization#fmt|Standard Library]] | ||
=Formatting= | =Formatting= | ||
==Conversion Characters== | |||
==<tt>%v</tt>== | |||
Print the value in the default format. | |||
==<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. | |||
==<tt>%T</tt>== | |||
A Go-syntax representation of the type of the value. | |||
==<tt>%%</tt>== | |||
A literal percent sign. Consumes no value. | |||
==Leading Zero Padding for Integers== | ==Leading Zero Padding for Integers== | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
Line 18: | Line 28: | ||
s := fmt.Sprintf("%6d", i) // will produce " 7" (five spaces) | s := fmt.Sprintf("%6d", i) // will produce " 7" (five spaces) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Functions= | =Functions= |
Revision as of 21:53, 22 December 2023
External
Internal
Formatting
Conversion Characters
%v
Print the value in the default format.
%+v
When printing structs, 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.
Leading Zero Padding for Integers
i := 7
s := fmt.Sprintf("%06d", i) // will produce "000007" (five zeroes)
Leading Space Padding for Integer
i := 7
s := fmt.Sprintf("%6d", i) // will produce " 7" (five spaces)
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(), Println()
Scanf(), Scanln()
Errorf()
Interfaces
fmt.Stringer
type Stringer interface {
String() string
}
Stringer
is implemented by any type that has a String()
method, which defines the "native" format for that value. The String()
method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print
. For a usage example, see: