0
0
GoHow-ToBeginner · 3 min read

How to Use fmt.Sprintf in Go: Simple Formatting Guide

In Go, fmt.Sprintf formats strings by inserting variables into a format string and returns the result without printing it. Use it by providing a format string with verbs like %s or %d followed by the values to insert.
📐

Syntax

The basic syntax of fmt.Sprintf is:

  • fmt.Sprintf(format string, values...)

Here, format string contains text and verbs like %s for strings, %d for integers, and %f for floats. The values are the variables you want to insert into the string.

go
result := fmt.Sprintf("Hello, %s! You have %d new messages.", "Alice", 5)
💻

Example

This example shows how to use fmt.Sprintf to create a formatted string with a name and a number, then print it.

go
package main

import (
	"fmt"
)

func main() {
	name := "Bob"
	count := 3
	message := fmt.Sprintf("Hello, %s! You have %d new notifications.", name, count)
	fmt.Println(message)
}
Output
Hello, Bob! You have 3 new notifications.
⚠️

Common Pitfalls

Common mistakes include:

  • Using fmt.Sprintf but forgetting to assign or use the returned string.
  • Mismatching verbs and variable types, like using %d for a string.
  • Confusing fmt.Sprintf with fmt.Printf, which prints directly instead of returning a string.
go
package main

import (
	"fmt"
)

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

	// Wrong: Using %d for a string causes runtime error
	// message := fmt.Sprintf("Name: %d", name) // This will cause an error

	// Correct:
	message := fmt.Sprintf("Name: %s, Age: %d", name, age)
	fmt.Println(message)
}
Output
Name: Eve, Age: 30
📊

Quick Reference

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

Key Takeaways

Use fmt.Sprintf to format strings and get the result as a string without printing.
Match format verbs like %s and %d correctly with variable types to avoid errors.
Remember fmt.Sprintf returns a string; use fmt.Printf to print directly.
Assign the result of fmt.Sprintf to a variable to use the formatted string later.
Common verbs include %s for strings, %d for integers, and %f for floats.