For example, we can have a program that returns the total price of a product based on the price of a single item and the total number of items bought. We can a string “Your total price is: {price*quantity}”. We then replace the placeholder value with the actual value from the expression.
This process is known as a string interpolation. It is a very useful feature as it allows us to add flexibility to our programs instead of hard coding values.
Go String Interpolation
We can include string interpolation in Go using the Sprintf function. This method is defined in the fmt package. Hence, we need to import it before using it:
Once imported, we can use it to interpolate strings.
Take the example shown below:
import "fmt"
funcmain() {
msg := "Your total price is %f."
price := 200.30
quantity := 10.0
total_price := price * (quantity)
output := fmt.Sprintf(msg, total_price)
fmt.Println(output)
}
In the example above, we use the Sprintf method to substitute for the specified values and save it to a variable. Keep in mind that you will need to use the format specifiers as discussed in the linked tutorial.
Conclusion
In this short article, we discussed how to perform string interpolation in the Go programming language. You may notice that the method of string interpolation in Go is very different from other languages such as Python. This is because Go is a statically typed language and it does matter the type of value you interpolate.
You can learn more about Go by checking our other tutorials on the topic.