Go by Example: String Formatting

Go provides several ways to format strings, including using fmt.Sprintf and fmt.Printf. fmt.Sprintf returns the formatted string, while fmt.Printf writes the formatted string to the standard output. Both functions use a similar syntax for specifying the format, using placeholders like %d for integers, %f for floating-point numbers, and %s for strings.

Here’s an example that demonstrates string formatting using fmt.Sprintf:

package main

import "fmt"

func main() {
	name := "John Doe"
	age := 30
	email := "john.doe@example.com"

	str := fmt.Sprintf("Name: %s\nAge: %d\nEmail: %s", name, age, email)
	fmt.Println(str)
}

In this example, three variables are defined: name, age, and email. The fmt.Sprintf function is used to format the values of these variables into a string, using placeholders for the various data types. The resulting string is then printed to the standard output using fmt.Println.

Here’s an equivalent example that uses fmt.Printf:

package main

import "fmt"

func main() {
	name := "John Doe"
	age := 30
	email := "john.doe@example.com"

	fmt.Printf("Name: %s\nAge: %d\nEmail: %s\n", name, age, email)
}

In this example, the same variables are defined and the same format string is used. However, instead of using fmt.Sprintf to return the formatted string, fmt.Printf is used to write the formatted string directly to the standard output.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *