Go’s fmt package provides powerful formatting tools, including formatting verbs, which define how values are displayed in formatted strings. These verbs are used with functions like fmt.Printf, fmt.Sprintf, and fmt.Fprintf to format and output text efficiently.
Commonly Used Formatting Verbs in Go
Below are various formatting verbs categorized by data types along with syntax and examples.
1. General Formatting Verbs
Verb
Description
%v
Default representation of a value
%+v
Like %v, but includes struct field names
%#v
Go syntax representation of a value
%T
Type of the value
%%
Prints a literal % symbol
Example:
package main
import "fmt"
func main() {
type Person struct {
Name string
Age int
}
p := Person{"Alice", 25}
fmt.Printf("Default format: %v\n", p)
fmt.Printf("With field names: %+v\n", p)
fmt.Printf("Go syntax format: %#v\n", p)
fmt.Printf("Type of variable: %T\n", p)
fmt.Printf("Percentage sign: %%\n")
}
Output:
Default format: {Alice 25}
With field names: {Name:Alice Age:25}
Go syntax format: main.Person{Name:"Alice", Age:25}
Type of variable: main.Person
Percentage sign: %
package main
import "fmt"
func main() {
val := true
fmt.Printf("Boolean: %t\n", val)
}
Output:
Boolean: true
6. Pointer Formatting Verbs
Verb
Description
%p
Prints a pointer’s memory address
Example:
package main
import "fmt"
func main() {
num := 10
fmt.Printf("Memory Address: %p\n", &num)
}
Output:
Memory Address: 0xc0000140a0 (example, varies per run)
7. Width and Precision Formatting
Verb
Description
%5d
Minimum width of 5 for integers
%10s
Minimum width of 10 for strings
%.2f
Two decimal places for floats
%6.2f
Width 6 and 2 decimal places
Example:
package main
import "fmt"
func main() {
num := 42
price := 3.14159
text := "Go"
fmt.Printf("Integer with width: |%5d|\n", num)
fmt.Printf("String with width: |%10s|\n", text)
fmt.Printf("Float with precision: |%.2f|\n", price)
fmt.Printf("Float with width and precision: |%6.2f|\n", price)
}
Output:
Integer with width: | 42|
String with width: | Go|
Float with precision: |3.14|
Float with width and precision: | 3.14|
Conclusion
Go’s formatting verbs allow precise control over output formatting. They are widely used in logging, debugging, and structured data output. The fmt package’s functions, such as Printf, Sprintf, and Fprintf, leverage these verbs to format data before displaying or storing it.