Formatting Strings in Go

Go follows the printf traditionarrow-up-right from the C language. In my opinion, string formatting/interpolation in Go is less elegant than Python's f-strings, unfortunately.

These following "formatting verbs" work with the formatting functions above:

Default Representation

The %v variant prints the Go syntax representation of a value, it's a nice default.

s := fmt.Sprintf("I am %v years old", 10)
// I am 10 years old

s := fmt.Sprintf("I am %v years old", "way too many")
// I am way too many years old

If you want to print in a more specific way, you can use the following formatting verbs:

String

s := fmt.Sprintf("I am %s years old", "way too many")
// I am way too many years old

Integer

Float

If you're interested in all the formatting options, you can look at the fmt package's docsarrow-up-right.

Assignment

Create a new variable called msg on line 9 and use the appropriate formatting function to return a string that contains the following:

  • Replace NAME with the variable name.

  • Replace OPENRATE with the variable openRate rounded to the nearest "tenths" place, e.g. 10.523 should be rounded down to 10.5.

  • The word percent should appear as part of the string following the open rate value.

  • Replace NEWLINE with the newline \narrow-up-right escape sequence.

With the inputs "Jimmy McGill" and 2.5, the expected output would be:

chevron-rightSolutionhashtag