search

What is the difference between Go's string concatenation and string interpolation?

In Go, string concatenation is the process of joining multiple strings together into a single string. This can be done using the + operator, like so:

str := "Hello " + "world"

String interpolation, on the other hand, is the process of inserting variables or expressions into a string. In Go, string interpolation is accomplished using the **fmt.Sprintf()** function, which allows you to insert values into a format string using placeholders:

name := "Alice"
age := 30
greeting := fmt.Sprintf("Hello, my name is %s and I am %d years old", name, age)

In this example, the **%s** and **%d** placeholders are replaced with the values of the **name** and **age** variables, respectively. The resulting string is stored in the **greeting** variable.

So, while string concatenation simply combines strings, string interpolation allows you to insert values into a string and format it in a particular way.

Related Questions You Might Be Interested