0
0
GoHow-ToBeginner · 3 min read

How to Use fmt.Printf in Go: Syntax and Examples

Use fmt.Printf in Go to print formatted text to the console. It takes a format string with verbs like %d for integers and %s for strings, followed by values to insert in place of those verbs.
📐

Syntax

The basic syntax of fmt.Printf is:

fmt.Printf(format string, values...)

Here:

  • format string: A string with placeholders (verbs) like %d, %s, %f that specify how to format the values.
  • values...: One or more values that replace the placeholders in order.
go
fmt.Printf("Hello %s, you have %d new messages.\n", "Alice", 5)
💻

Example

This example shows how to print a greeting with a name and a number using fmt.Printf. It demonstrates string and integer formatting.

go
package main

import "fmt"

func main() {
    name := "Alice"
    messages := 5
    fmt.Printf("Hello %s, you have %d new messages.\n", name, messages)
}
Output
Hello Alice, you have 5 new messages.
⚠️

Common Pitfalls

Common mistakes when using fmt.Printf include:

  • Not matching the number of verbs with the number of values, which causes runtime errors.
  • Using the wrong verb for a value type, like %d for a string.
  • Forgetting to add \n at the end of the format string, which keeps the cursor on the same line.

Example of wrong and right usage:

go
package main

import "fmt"

func main() {
    // Wrong: missing value for %d
    // fmt.Printf("Count: %d\n") // This causes an error

    // Wrong: wrong verb for string
    // fmt.Printf("Name: %d\n", "Bob") // This causes an error

    // Right:
    fmt.Printf("Count: %d\n", 10)
    fmt.Printf("Name: %s\n", "Bob")
}
Output
Count: 10 Name: Bob
📊

Quick Reference

VerbDescriptionExample
%dDecimal integer42
%sString"hello"
%fFloating-point number3.14
%tBooleantrue
%vDefault format for any valuevaries
%%Literal percent sign%

Key Takeaways

Use fmt.Printf with a format string and matching values to print formatted output.
Match verbs like %d and %s correctly to the value types to avoid errors.
Always include \n at the end of the format string to move to the next line.
Common verbs include %d for integers, %s for strings, and %f for floats.
fmt.Printf does not add a newline automatically; you must include it in the format string.