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:

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

output:

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