Go Package fmt: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(41 intermediate revisions by the same user not shown)
Line 4: Line 4:


=Internal=
=Internal=
* [[Go_Language_Modularization#fmt|Standard Library]]
* [[Go_Strings#String_Manipulation_and_Processing_in_Go|String Manipulation and Processing in Go]]


* [[Go Concepts - Standard Library#Packages|Standard Library]]
=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.


=Functions=
"%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>[https://golang.org/pkg/fmt/#Println fmt.Println()]</tt>
 
==<tt>fmt.Printf()</tt>==
 
* <tt>[https://golang.org/pkg/fmt/#Printf fmt.Printf()]</tt>
 
Prints according to a format specifier. Format specifier documentation https://golang.org/pkg/fmt
 
===Pointers===


<pre>
===<tt>%+v</tt>===
fmt.Printf("%p\n", sPtr)
When printing structs, the plus flag <code>%+v</code> adds field names.
</pre>
===<tt>%#v</tt>===
A Go-syntax representation of the value.


"%p" prepend the "0x" prefix.
<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>
Pointers can be also represented using "%X" (base 16, upper case characters).
&errors.errorString{s:"something"}
 
</font>
===Ints===
 
<pre>
fmt.Printf("%d\n",i)
</pre>


===<tt>%T</tt>===
A Go-syntax representation of the type of the value.
===<tt>%%</tt>===
A literal percent sign. Consumes no value.
===Strings===
<syntaxhighlight lang='go'>
color := "blue"
fmt.Printf("The color is %s\n", color)
</syntaxhighlight>
===Integers===
<syntaxhighlight lang='go'>
size := 1
fmt.Printf("The size is %d\n", size)
</syntaxhighlight>
===Characters===
===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


<pre>
<syntaxhighlight lang='go'>
fmt.Printf("%c\n",i)
f := 1.0
</pre>
fmt.Printf("The floating point value is %f\n", f)
</syntaxhighlight>
====<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
====<tt>%X</tt>====
Upper-case hexadecimal notation, e.g. -0X1.23ABCP+20


===Boolean Values===
===<tt>%w</tt>===
Used with <code>fmt.Errorf()</code> to [[Go_Language_Error_Handling#Wrap_the_Error_Instance|wrap errors]].


<pre>
==Pointers==
fmt.Printf("%t\n",b)
{{Internal|Pointers_in_Go#Displaying_Pointers|Pointers in Go &#124; Displaying Pointers}}
</pre>


==<tt>fmt.Scanf()</tt>==
==Structs==
{{Internal|Go_Structs#Printing_Structs|Go Structs &#124; Printing Structs}}


* <tt>[https://golang.org/pkg/fmt/#Scanf fmt.Scanf()]</tt>
==Padding==
===Leading Zero Padding for Integers===
<syntaxhighlight lang='go'>
i := 7
s := fmt.Sprintf("%06d", i) // will produce "000007" (five zeroes)
</syntaxhighlight>


==<tt>fmt.Scanln()</tt>==
===Leading Space Padding for Integer===
<syntaxhighlight lang='go'>
i := 7
s := fmt.Sprintf("%6d", i) // will produce "    7" (five spaces)
</syntaxhighlight>
===String Padding===
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:
<syntaxhighlight lang='go'>
fmt.Sprintf("%*s", 10, "test")
</syntaxhighlight>


* <tt>[https://golang.org/pkg/fmt/#Scanln fmt.Scanln()]</tt>
=Functions=
==<tt>Sprintf()</tt>==
Format a string and returns it as a result:
<syntaxhighlight lang='go'>
message := fmt.Sprintf("Hi, %v. Welcome!", name)
</syntaxhighlight>
For more details on the format string, see: {{Internal|Go_Printing_to_Stdout_and_Stderr#fmt.Printf.28.29|<tt>Printf()</tt> Format String}}


<pre>
==<span id='fmt.Printf.28.29.2C_fmt.Println.28.29'></span><tt>Printf()</tt>, <tt>Println()</tt>==
var line string
{{Internal|Go_Printing_to_Stdout_and_Stderr#fmt_Functions|Printing to <tt>stdout</tt> and <tt>stderr</tt>}}
fmt.Scanln(&line)
</pre>


==<tt>fmt.Errorf()</tt>==
==<span id='fmt.Scanf.28.29.2C_fmt.Scanln.28.29'></span><tt>Scanf()</tt>, <tt>Scanln()</tt>==
{{Internal|Handling_stdin_in_Go#Handling_stdin_with_fmt_Functions|Handling <tt>stdin</tt> in Go}}


* <tt>[https://golang.org/pkg/fmt/#Errorf fmt.Errorf()]</tt>
==<tt><span id='fmt.Errorf.28.29'></span>Errorf()</tt>==
{{Internal|Go_Language_Error_Handling#fmt.Errorf.28.29|Go Language Error Handling}}


<tt>Errorf</tt> formats according to a format specifier and returns the string as a value that satisfies <tt>error</tt>. For more on error handling see [[Go_Concepts_-_Error_Handling#Creating_Custom_error_Instances|error handling]].
=Interfaces=
==<tt>fmt.Stringer</tt>==
<syntaxhighlight lang='go'>
type Stringer interface {
  String() string
}
</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}}

Latest revision as of 01:49, 13 June 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.

"%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

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

Integers

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

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)

%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

%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)

Leading Space Padding for Integer

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

String Padding

Left:

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

Right:

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

Padding quantity specified as parameter of the function:

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

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

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:

The Equivalent of Java toString() in Go