0
0
GoHow-ToBeginner · 3 min read

How to Format String in Go: Syntax and Examples

In Go, you format strings using fmt.Sprintf, which works like a template where placeholders are replaced by values. Use verbs like %s for strings, %d for integers, and %f for floats inside the format string.
📐

Syntax

The basic syntax for formatting strings in Go uses fmt.Sprintf:

  • fmt.Sprintf(format string, values...) returns a formatted string.
  • The format string contains verbs like %s, %d, and %f as placeholders.
  • values... are the variables you want to insert into the string.
go
formatted := fmt.Sprintf("Hello, %s! You have %d new messages.", "Alice", 5)
💻

Example

This example shows how to format a greeting message with a name and a number using fmt.Sprintf. It prints the formatted string.

go
package main

import (
	"fmt"
)

func main() {
	name := "Alice"
	messages := 5
	formatted := fmt.Sprintf("Hello, %s! You have %d new messages.", name, messages)
	fmt.Println(formatted)
}
Output
Hello, Alice! You have 5 new messages.
⚠️

Common Pitfalls

Common mistakes include:

  • Using the wrong verb for the data type, like %d for a string.
  • Not matching the number of verbs with the number of values.
  • Forgetting to import fmt package.

Here is an example of a wrong and right way:

go
package main

import (
	"fmt"
)

func main() {
	name := "Bob"
	age := 30

	// Wrong: using %d for string
	// formatted := fmt.Sprintf("Name: %d, Age: %d", name, age) // This causes a runtime error

	// Right:
	formatted := fmt.Sprintf("Name: %s, Age: %d", name, age)
	fmt.Println(formatted)
}
Output
Name: Bob, Age: 30
📊

Quick Reference

VerbDescriptionExample
%sString"hello"
%dInteger (decimal)123
%fFloating point number3.14
%tBooleantrue
%vDefault formatany value
%%Literal percent sign%

Key Takeaways

Use fmt.Sprintf with format verbs like %s, %d, and %f to format strings in Go.
Match the number and type of verbs with the values you provide to avoid errors.
Always import the fmt package to use formatting functions.
Use %v for a default format when unsure about the type.
Remember %% to print a literal percent sign in formatted strings.