In Go, Printf supports a variety of format specifiers that allow you to control how different types of data are displayed. Here are some commonly used format specifiers:
Common Format Specifiers:
-
String and Character:
%s- String%q- Double-quoted string (with escape characters)%c- Character (rune)
-
Integer:
%d- Decimal integer%b- Binary representation%o- Octal representation%x- Hexadecimal representation (lowercase)%X- Hexadecimal representation (uppercase)
-
Floating-Point:
%f- Decimal point and exponent (default)%e- Scientific notation (lowercase)%E- Scientific notation (uppercase)%g- Uses the shortest representation between%fand%e%.nf- Floating-point withndecimal places (e.g.,%.2ffor two decimal places)
-
Boolean:
%t- Boolean (true or false)
-
Pointer:
%p- Pointer address in hexadecimal
-
Default Format:
%v- Default format for the value%+v- Struct with field names%#v- Go-syntax representation of the value
-
Width and Precision:
%5d- Right-aligned integer with a width of 5%-5s- Left-aligned string with a width of 5%10.2f- 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
isStudent := true
fmt.Printf("Name: %s\n", name)
fmt.Printf("Age: %d\n", age)
fmt.Printf("Height: %.1f\n", height)
fmt.Printf("Is Student: %t\n", isStudent)
}
Output:
Name: Alice
Age: 30
Height: 5.6
Is Student: true
Feel free to experiment with these format specifiers to see how they affect the output!
