What You'll Learn

Are you ready to explore combining text with variables in Go using fmt.Sprintf? This versatile feature makes it effortless to create dynamic and readable strings by embedding variables directly within them.

Code Example

For a trip planning scenario, consider these variables:

// Travel variables
var destination string = "Paris"
var numberOfDays int = 5
var tripCost float64 = 1200.50 // Notice how we can store numbers in variables that are not integers!

Using fmt.Sprintf enables you to neatly include variable values in your text output:

// Using fmt.Sprintf for travel details
package main

import (
    "fmt"
)

func main() {
    var destination string = "Paris"
    var numberOfDays int = 5
    var tripCost float64 = 1200.50

    details := fmt.Sprintf("I am planning a trip to %s.", destination)
    fmt.Println(details)
    details = fmt.Sprintf("The trip will be for %d days.", numberOfDays)
    fmt.Println(details)
    details = fmt.Sprintf("The estimated cost of the trip is $%.2f.", tripCost)
    fmt.Println(details)
}

output:

I am planning a trip to Paris.
The trip will be for 5 days.
The estimated cost of the trip is $1200.50.

Format specifiers in fmt.Sprintf help format the inserted variables in specific ways:

  • %s: Used for strings. In our code, %s is replacedwith the value of destination.
  • %d: Used for integers. In our code, %d inserts the value of numberOfDays.
  • %f: For floating-point numbers. By default, it includes six decimal places.
    • %.2f: This limits the floating-point number to two decimal places.In our code, tripCost is limited to only 2 decimal places.
Why It Matters

fmt.Sprintf offers a concise and readable way to incorporate variables into strings, enhancing code clarity. It's especially useful for outputting data in a more engaging and informative manner. Through practice, you'll become comfortable with this skill, which is crucial for effective Go programming.

Let's dive into the practice exercises!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal