To control the width and alignment of printed data with fmt
in Go, you can use the format specifiers and flags provided by the package. Here are some ways to achieve this:
Width control:
%Nd
), where N
is the desired minimum width.-
flag (%Nd
).fmt.Printf("|%10d|\n", 42) // Output: | 42|
fmt.Printf("|%-10d|\n", 42) // Output: |42 |
Precision control:
%N.Mf
), where N
is the minimum width and M
is the precision.fmt.Printf("|%8.2f|\n", 3.14159) // Output: | 3.14|
Arbitrary width and alignment:
*
instead of a number in the format specifier, and passing the values as arguments.width := 10
fmt.Printf("|%*d|\n", width, 42) // Output: | 42|
alignment := "-"
fmt.Printf("|%*s|\n", -width, "hello") // Output: |hello |
These examples demonstrate some of the basic techniques to control the width and alignment of printed data using fmt
in Go. You can combine different flags and specifiers to achieve more specific formatting as required.