Go offers excellent support for string formatting in
the |
|
package main
|
|
import "fmt"
import "os"
|
|
type point struct {
x, y int
}
|
|
func main() {
|
|
Go offers several printing “verbs” designed to
format general Go values. For example, this prints
an instance of our |
p := point{1, 2}
fmt.Printf("%v\n", p)
|
If the value is a struct, the |
fmt.Printf("%+v\n", p)
|
The |
fmt.Printf("%#v\n", p)
|
To print the type of a value, use |
fmt.Printf("%T\n", p)
|
Formatting booleans is straight-forward. |
fmt.Printf("%t\n", true)
|
There are many options for formatting integers.
Use |
fmt.Printf("%d\n", 123)
|
This prints a binary representation. |
fmt.Printf("%b\n", 14)
|
This prints the character corresponding to the given integer. |
fmt.Printf("%c\n", 33)
|
|
fmt.Printf("%x\n", 456)
|
There are also several formatting options for
floats. For basic decimal formatting use |
fmt.Printf("%f\n", 78.9)
|
|
fmt.Printf("%e\n", 123400000.0)
fmt.Printf("%E\n", 123400000.0)
|
For basic string printing use |
fmt.Printf("%s\n", "\"string\"")
|
To double-quote strings as in Go source, use |
fmt.Printf("%q\n", "\"string\"")
|
As with integers as seen earlier, |
fmt.Printf("%x\n", "hex this")
|
To print a representation of a pointer, use |
fmt.Printf("%p\n", &p)
|
When formatting numbers you will often want to
control the width and precision of the resulting
figure. To specify the width of an integer, use a
number after the |
fmt.Printf("|%6d|%6d|\n", 12, 345)
|
You can also specify the width of printed floats, though usually you’ll also want to restrict the decimal precision at the same time with the width.precision syntax. |
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
|
To left-justify, use the |
fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)
|
You may also want to control width when formatting strings, especially to ensure that they align in table-like output. For basic right-justified width. |
fmt.Printf("|%6s|%6s|\n", "foo", "b")
|
To left-justify use the |
fmt.Printf("|%-6s|%-6s|\n", "foo", "b")
|
So far we’ve seen |
s := fmt.Sprintf("a %s", "string")
fmt.Println(s)
|
You can format+print to |
fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
|
$ go run string-formatting.go
{1 2}
{x:1 y:2}
main.point{x:1, y:2}
main.point
true
123
1110
!
1c8
78.900000
1.234000e+08
1.234000E+08
"string"
"\"string\""
6865782074686973
0x42135100
| 12| 345|
| 1.20| 3.45|
|1.20 |3.45 |
| foo| b|
|foo |b |
a string
an error
|
Next example: Regular Expressions.