What is String Interpolation
String interpolation is the process of inserting data from a variable or expression into a placeholder within a string. It is an important feature because it enables us to provide our applications more readable and flexible instead of hard coding.
Different formatting functions in GO
The following table describes the functions provided by the fmt package, which can format strings
| Name | Description |
|---|---|
Sprintf(t, ...vals) |
This function returns a string, which is created by processing the templatet. The remaining arguments are used as values for the template verbs. |
Printf(t, ...vals) |
This function creates a string by processing the templatet. The remaining arguments are used as values for the template verbs. The string is written to the standard out. |
Fprintf(writer, t, ...vals) |
This function creates a string by processing the template t. The remaining arguments are used as values for the template verbs. The string is written to a Writer. |
Errorf(t, ...values) |
This function creates anerrorby processing the templatet. The remaining arguments are used as values for the template verbs. The result is anerrorvalue whoseErrormethod returns the formatted string. |
Using General-Purpose Formatting Verbs
The general-purpose verbs can be used to display any value as described in below table.
| Verb | Description |
|---|---|
%v |
This verb displays the default format for the value. Modifying the verb with a plus sign (%+v) includes field names when writing out struct values. |
%#v |
This verb displays a value in a format that could be used to re-create the value in a Go code file. |
%T |
This verb displays the Go type of a value. |
Using Integer Formatting Verbs
The following table describes the formatting verbs for integer values, regardless of their size.
| Verb | Description |
|---|---|
%b |
This verb displays an integer value as a binary string. |
%d |
This verb displays an integer value as a decimal string. This is the default format for integer values, applied when the%vverb is used. |
%o, %O |
These verbs display an integer value as an octal string. The%Overb adds the0oprefix. |
%x, %X |
These verbs display an integer value as a hexadecimal string. The letters A–F are displayed in lowercase by the%xverb and in uppercase by the%Xverb. |
Using Floating-Point Formatting Verbs
The following table describes the formatting verbs for floating-point values, which can be applied to bothfloat32andfloat64values.
| Verb | Description |
|---|---|
%b |
This verb displays a floating-point value with an exponent and without a decimal place. |
%e, %E |
These verbs display a floating-point value with an exponent and a decimal place. The%euses a lowercase exponent indicator, while%Euses an uppercase indicator. |
%f, %F |
These verbs display a floating-point value with a decimal place but no exponent. The%fand%Fverbs produce the same output. |
%g |
This verb adapts to the value it displays. The%eformat is used for values with large exponents, and the%fformat is used otherwise. This is the default format, applied when the%vverb is used. |
%G |
This verb adapts to the value it displays. The%Eformat is used for values with large exponents, and the%fformat is used otherwise. |
%x, %X |
These verbs display a floating-point value in hexadecimal notation, with lowercase (%x) or uppercase (%X) letters. |
Using String and Character Formatting Verbs
The below table describes the formatting verbs for strings
| Verb | Description |
|---|---|
%s |
This verb displays a string. This is the default format, applied when the%vverb is used. |
%c |
This verb displays a character. Care must be taken to avoid slicing strings into individual bytes, as explained in the text after the table. |
%U |
This verb displays a character in the Unicode format so that the output begins withU+followed by a hexadecimal character code. |
Using Boolean Formatting Verb
We can use %t where this verb formatsboolvalues and
displaystrueorfalse. Here we have a simple go code where we check
the length of a variable and print the Boolean value.
package main
import "fmt"
func Printfln(template string, values ...interface{}) {
fmt.Printf(template+"\n", values...)
}
func main() {
name := "GoLinuxCloud"
Printfln("Bool: %t", len(name) > 1)
Printfln("Bool: %t", len(name) > 100)
}
Output:
$ go run main.go
Bool: true
Bool: false
Using Pointer Formatting Verb
We can use %p where this verb displays a hexadecimal representation of
the pointer’s storage location. Here is a small code to demonstrate this
verb:
package main
import "fmt"
func Printfln(template string, values ...interface{}) {
fmt.Printf(template+"\n", values...)
}
func main() {
name := "GoLinuxCloud"
Printfln("Pointer: %p", &name)
}
In the output we can see hexadecimal format of the pointer location:
$ go run main.go
Pointer: 0xc000010230
Method 1: Using Sprintf() function
We can include string interpolation in Go using the Sprintf()
function:
func Sprint(a ...any) string: Sprint formats using the default formats
for its operands and returns the resulting string. Spaces are added
between operands when neither is a string.
This method is defined in the fmt package. Hence, we need to import it
before using it:
import "fmt"
Here’s an example of using the Sprintf() function:
package main
import "fmt"
func main() {
thisYear := 2022
thisMonth := 9
thisDay := 13
thisHour := 10
thisMinute := 30
thisSecond := 45
// date is a string which relaces variables into placeholders
thisDate := fmt.Sprintf("%d-%d-%d", thisYear, thisMonth, thisDay)
thisTime := fmt.Sprintf("%d:%d:%d", thisHour, thisMinute, thisSecond)
dateTime := fmt.Sprintf("Date: %s, Time: %s", thisDate, thisTime)
// print the string variables
fmt.Println(thisDate)
fmt.Println(thisTime)
fmt.Println(dateTime)
}
Output:
$ go run main.go
2022-9-13
10:30:45
Date: 2022-9-13, Time: 10:30:45
Method 2: Using Printf() function
The Printf() function can be used to print the formatted string to the
console. The only difference between Sprintf() and Printf() is that
Sprintf() writes data into a character array, while Printf() writes
data to stdout, the standard output device.
func Printf(format string, a ...any) (n int, err error): Printf
formats according to a format specifier and writes to standard output.
It returns the number of bytes written and any write error encountered.
Here’s an example of using the Printf() function:
package main
import "fmt"
func main() {
thisYear := 2022
thisMonth := 9
thisDay := 13
thisHour := 10
thisMinute := 30
thisSecond := 45
// directly print formatted string to console
fmt.Printf("%d-%d-%d", thisYear, thisMonth, thisDay)
fmt.Println()
fmt.Printf("%d:%d:%d", thisHour, thisMinute, thisSecond)
}
Output:
$ go run main.go
2022-9-13
10:30:45
Method 3: Using Fprintf() function
The syntax here is
func fmt.Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
The fmt package also provides functions for writing formatted strings
to a Writer, Fprintf formats according to a format specifier and writes
to w. It returns the number of bytes written and any write error
encountered.
package main
import (
"fmt"
"io"
"strings"
)
func writeFormatted(writer io.Writer, template string, vals ...interface{}) {
fmt.Fprintf(writer, template, vals...)
}
func main() {
var writer strings.Builder
template := "Name: %s, Category: %s, Price: $%.2f"
writeFormatted(&writer, template, "Car", "Honda", float64(3500))
fmt.Println(writer.String())
}
ThewriteFormattedfunction uses thefmt.Fprintffunction to write a
string formatted with a template to aWriter. Compile and execute the
project, and you will see the following output:
$ go run main.go
Name: Car, Category: Honda, Price: $3500.00
Method-4: Using Errorf() function
The syntax for declaration is
func fmt.Errorf(format string, a ...interface{}) error
Errorf formats according to a format specifier and returns the string as
a value that satisfies error.If the format specifier includes a %w
verb with an error operand, the returned error will implement an Unwrap
method returning the operand. It is invalid to include more than one %w
verb or to supply it with an operand that does not implement the error
interface. The %w verb is otherwise a synonym for %v.
Errorf() should not end with punctuation or
newlines and should not be capitalized.
package main
// Importing fmt
import (
"fmt"
)
// Calling main
func main() {
// Declaring some constant variables
const (
Name = "Deepak"
Age = 34
Salary = 1500.50
)
// Calling the Errorf() function with verb
// %v which is used for a string character
// %d is used for integer character
// %.2f is used to specify the number of digits after the decimal place in floating character
err := fmt.Errorf("employee %v of age %d has salary of %.2f", Name, Age, Salary)
// Printing the error message
fmt.Println(err.Error())
}
Output:
$ go run main.go
employee Deepak of age 34 has salary of 1500.50
Summary
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.

![Golang string interpolation Explained [With Examples]](/golang-string-interpolation/golang_string_interpolation.jpg)
