Lesson 4
Combining Text with Variables in Go Using fmt.Sprintf
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:

Go
1// Travel variables 2var destination string = "Paris" 3var numberOfDays int = 5 4var 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:

Go
1// Using fmt.Sprintf for travel details 2package main 3 4import ( 5 "fmt" 6) 7 8func main() { 9 var destination string = "Paris" 10 var numberOfDays int = 5 11 var tripCost float64 = 1200.50 12 13 details := fmt.Sprintf("I am planning a trip to %s.", destination) 14 fmt.Println(details) 15 details = fmt.Sprintf("The trip will be for %d days.", numberOfDays) 16 fmt.Println(details) 17 details = fmt.Sprintf("The estimated cost of the trip is $%.2f.", tripCost) 18 fmt.Println(details) 19}

output:

Plain text
1I am planning a trip to Paris. 2The trip will be for 5 days. 3The 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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.