Summary - fmt package
- Go course
- Intermediate
- Lesson 58/80
- 4 min
Combine Printf, Sprintf and Errorf to write a reporter.
fmt package summary
Three families, three targets: Print* → stdout, Fprint* → io.Writer, Sprint* → string; plus Errorf → error. Verbs: %v %+v %#v %T general, %d %x %b integers, %s %q text, %f %.2f %e decimals. Width/alignment: %8s, %-8s, %08d. String() for your own types, %w for errors.
Explicit argument indexes
To use the same value several times, the %[n] form refers to an argument by its number:
fmt.Printf("%[1]d onluk = %[1]x onaltılık = %[1]b ikili\n", 10)
// 10 onluk = a onaltılık = 1010 ikiliIt is also handy in translation strings where word order changes by language.
Practice Number bases
Print the number 42 in decimal, hex and binary with a single Printf using argument indexes: "42 2a 101010".
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
fmt.Printf("%[1]d %[1]x %[1]b\n", 42)
}Expected output
42 2a 101010
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which shows both a value's field names and its type name?
- %s
- %d
- %#v Correct answer
- %v
Explanation: %#v writes the value in Go syntax: main.Kisi{Ad:"Ada", Yas:36}. %+v shows field names but not the type.
2 Same argument
fmt.Printf("%d = %____x
", 255)
fmt.Printf("%d = %[1]x
", 255)
Explanation: %[1]x reuses the first argument and writes it in hex.
3 Group summary
| Term | Meaning |
|---|---|
Sprintf |
Produces a string |
Fprintf |
Writes to a Writer |
Errorf + %w |
Wraps an error |
String() |
Custom display |