Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
+ operator. However, in Go, the
+ operator is used for arithmetic operations and cannot be used for string concatenation.
Instead, Go provides the
fmt.Sprintf function for string formatting. This function works similarly to the
printf function in C and other languages. It takes a format string and a list of values to be formatted and returns a formatted string.
To concatenate two strings in Go, you can use the
fmt.Sprintf function with a format string that includes the two strings to be concatenated. Here’s an example:
str1 := "Hello, "
str2 := "world!"
result := fmt.Sprintf("%s%s", str1, str2)
// result is "Hello, world!"
In this example, the
fmt.Sprintf function takes a format string of
"%s%s", which includes two
%s placeholders for strings. The function then takes the values of
str2 and substitutes them into the placeholders to create the concatenated string.
By using the
fmt.Sprintf function, you can easily concatenate strings in Go without having to resort to complex string manipulation.