How to use format verbs (e.g., %d, %s, %f) to control data output in fmt in Go?

In Go, format verbs such as %d, %s, %f, etc. are used with the fmt package to control data output. These verbs are placeholders that are replaced with the actual values when printing.

Here is how you can use format verbs to control data output in Go:

  1. %d - This verb is used to format integers.

    age := 27 fmt.Printf("My age is %d\n", age)

    Output: My age is 27

  2. %s - This verb is used to format strings.

    name := "John" fmt.Printf("My name is %s\n", name)

    Output: My name is John

  3. %f - This verb is used to format floating-point numbers.

    temperature := 23.5 fmt.Printf("The temperature is %f\n", temperature)

    Output: The temperature is 23.500000

  4. %t - This verb is used to format boolean values (true or false).

    isRaining := true fmt.Printf("Is it raining? %t\n", isRaining)

    Output: Is it raining? true

  5. %v - This verb is a more general verb that can format values of different types.

    value := 42 fmt.Printf("The value is %v\n", value)

    Output: The value is 42

You can also specify additional formatting options, such as field width and precision, by including them in the format specifier.

quantity := 5 price := 9.99 fmt.Printf("Total: %d items, price per item: $%.2f\n", quantity, price)

Output: Total: 5 items, price per item: $9.99

Format verbs are very flexible and can be combined with other formatting options to customize the output according to your needs.