How to concatenate two strings in Go lang – Programming Code Examples
Go

How to concatenate two strings in Go lang3 min read

In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator. It is also known as a concatenation operator.

Example:




Using bytes.Buffer: You can also create a string by concatenating the bytes of the strings using bytes.Buffer with WriteString() method. It is defined under bytes package. It prevents the generation of the unnecessary string object, means it doesn’t generate a new string like in + operator from two or more strings.

Example:

Using Sprintf: In Go language, you can also concatenate string using Sprintf() method.

Example:

Using += operator or String append: In Go strings, you are allowed to append a string using += operator. This operator adds a new or given string to the end of the specified string.

Example:

  • String: GeeksforGeeksPortal
  • Using Join() function: This function concatenates all the elements present in the slice of string into a single string. This function is available in string package.Syntax:

Here, str is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the final string.

Example:

Source: https://www.geeksforgeeks.org/different-ways-to-concatenate-two-strings-in-golang/?ref=leftbar-rightbar

Leave a Comment