How to format and print data to a string using fmt.Sprintf in Go?

In Go, fmt.Sprintf is used to format and return the formatted string. This function behaves similarly to fmt.Printf, but instead of printing the formatted string to the standard output, it returns the formatted string itself. Here's an example of how to use fmt.Sprintf to format and print data to a string:

package main import ( "fmt" ) func main() { name := "John" age := 30 height := 5.9 // Format and print the data to a string str := fmt.Sprintf("Name: %s, Age: %d, Height: %.2f", name, age, height) // Print the formatted string fmt.Println(str) }

Output:

Name: John, Age: 30, Height: 5.90

In the example above, we create variables for name, age, and height. Then, we use fmt.Sprintf to format the data and store it in the str variable. We provide a format string that includes placeholders (%s, %d, %f) to represent the values of the variables.

In the format string, %s is used for strings, %d is used for integers, and %f is used for floating-point numbers. Additionally, we can specify precision for floating-point numbers using the format specifier %.2f, which limits the output to 2 decimal places.

Finally, we print the formatted string using fmt.Println.