fmt formatting verbs
- Version
- 1.27
- Review
- Draft
Summary#
fmt.Printf writes formatted text, and fmt.Sprintf returns it. A verb such as %d selects a representation. Flags, a width and a precision go between % and the verb letter.
Syntax#
fmt.Printf("%s has %d items\n", name, count)
label := fmt.Sprintf("%08.2f", amount)
Example#
package main
import "fmt"
type point struct{ X, Y int }
func main() {
p := point{X: 3, Y: -4}
fmt.Printf("%v\n", p) // values
fmt.Printf("%+v\n", p) // with field names
fmt.Printf("%#v\n", p) // Go syntax
fmt.Printf("%T\n", p) // type
fmt.Printf("%q %t\n", "tab\there", true)
fmt.Printf("[%5d] [%-5d] [%05d] [%+d]\n", 42, 42, 42, 42)
fmt.Printf("[%8.3f] [%.2f%%]\n", 3.14159, 99.5)
fmt.Printf("%x %X %08b\n", 255, "Go", 5)
fmt.Printf("[%-4s] [%4s]\n", "go", "go")
id := fmt.Sprintf("job-%04d", 7)
fmt.Println(id)
}
Expected output#
{3 -4}
{X:3 Y:-4}
main.point{X:3, Y:-4}
main.point
"tab\there" true
[ 42] [42 ] [00042] [+42]
[ 3.142] [99.50%]
ff 476F 00000101
[go ] [ go]
job-0007
Common mistakes#
A wrong verb or argument count does not stop the program. The output contains text such as %!d(string=seven). Run go vet to catch these calls. Do not pass untrusted text as the format string; use fmt.Print(text) or fmt.Printf("%s", text).
Version applicability#
The verbs, flags, width and precision in the example are available from Go 1.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0