Can you provide an example of using the formatted output Printf function?

Certainly! The Printf function from the fmt package in Go is used for formatted output. It allows you to format strings with placeholders for variables, making it useful for creating more complex output.

Example of Using Printf

Here’s a simple example that demonstrates how to use Printf to format output:

package main

import "fmt"

func main() {
    name := "Alice"
    age := 30
    height := 5.6

    // Using Printf to format the output
    fmt.Printf("Name: %s\nAge: %d\nHeight: %.1f feet\n", name, age, height)
}

Explanation of the Code

  1. Importing the Package:

    • We import the fmt package to use the Printf function.
  2. Defining Variables:

    • We define three variables: name, age, and height.
  3. Using Printf:

    • The Printf function is called with a format string:
      • %s is a placeholder for a string (used for name).
      • %d is a placeholder for an integer (used for age).
      • %.1f is a placeholder for a floating-point number with one decimal place (used for height).
    • The variables are passed as additional arguments to Printf, which replaces the placeholders with their corresponding values.

Output

When you run the program, the output will be:

Name: Alice
Age: 30
Height: 5.6 feet

Conclusion

Using Printf allows you to create formatted strings that can include various data types, making it a powerful tool for outputting information in a structured way. If you have any further questions or need more examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!