golang

Golang String Interpolation

String interpolation refers to the process of replacing values of a variable or expression into a placeholder inside a string.

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:

import "fmt"

Once imported, we can use it to interpolate strings.

Take the example shown below:

package main
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 following tutorial:

https://linuxhint.com/go-sprintf

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list