How to control the width and alignment of printed data with fmt in Go?

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:

  1. Width control:

    • To specify the minimum width of a printed value, you can use the width specifier (%Nd), where N is the desired minimum width.
    • By default, values are right-aligned within the specified width. To left-align the value, you can use the - flag (%Nd).
    • For example:
    fmt.Printf("|%10d|\n", 42) // Output: | 42| fmt.Printf("|%-10d|\n", 42) // Output: |42 |
  2. Precision control:

    • For floating-point values, you can specify the width and precision of the printed value using the format specifier (%N.Mf), where N is the minimum width and M is the precision.
    • For example:
    fmt.Printf("|%8.2f|\n", 3.14159) // Output: | 3.14|
  3. Arbitrary width and alignment:

    • If you don't know the width or alignment at compile time, you can use the width and alignment parameters dynamically by using * instead of a number in the format specifier, and passing the values as arguments.
    • For example:
    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.