Here are some common format specifiers used in Go's Printf function:
Common Format Specifiers:
-
String and Character:
%s- Formats a string.%q- Formats a string as a double-quoted string (with escape characters).%c- Formats a single character (rune).
-
Integer:
%d- Formats a decimal integer.%b- Formats an integer in binary representation.%o- Formats an integer in octal representation.%x- Formats an integer in hexadecimal (lowercase).%X- Formats an integer in hexadecimal (uppercase).
-
Floating-Point:
%f- Formats a floating-point number in decimal notation.%e- Formats a floating-point number in scientific notation (lowercase).%E- Formats a floating-point number in scientific notation (uppercase).%g- Formats a floating-point number using the shortest representation between%fand%e.
-
Boolean:
%t- Formats a boolean value (true or false).
-
Pointer:
%p- Formats a pointer address in hexadecimal.
-
Default Format:
%v- Formats the value in its default format.%+v- Formats a struct with field names.%#v- Formats the value in Go-syntax representation.
-
Width and Precision:
%5d- Right-aligns an integer with a width of 5.%-5s- Left-aligns a string with a width of 5.%10.2f- Formats a floating-point number with a width of 10 and 2 decimal places.
Example Usage:
package main
import "fmt"
func main() {
name := "Alice"
age := 30
height := 5.6
fmt.Printf("Name: %s\n", name)
fmt.Printf("Age: %d\n", age)
fmt.Printf("Height: %.1f\n", height)
}
Output:
Name: Alice
Age: 30
Height: 5.6
These format specifiers provide flexibility in how you present data in your Go programs.
