In this guide, we will teach you how to work with strings, from the basics of creating a basic string to various ways of how to create a multi-line string.
Golang Basic String
In go, we can create a string by enclosing the characters inside double-quotes as shown below:
You can print a string by using the methods in the fmt package. For example, we can use the Println method to print a string as:
import "fmt"
func main() {
fmt.Println("this is a string")
}
The Println method should take the provided string and output it into the console.
If you want to create a string variable, you can use the var keyword as shown below:
str = "this is a string"
The above technique creates a variable called “str” of type string. We then assign a value to the variable using the assignment operator.
You can also use the string literal method of creating a string variable. This allows the compiler to determine the type of the variable.
An example is as shown as:
Golang Multi-Line String
In Go, we can create a multi-line string in two principal methods. The first method is to use a raw string literal.
Raw String Literal
To create a multi-line string using a raw string literal, we enclose the string inside a pair of back-tick chracters (“).
This method of string creation does not interpret whitespace characters such as \n, \t, etc. This is what makes this technique very useful.
For example, to create a multi-line string using a raw string literal, we can do:
welcome to Linuxhint.
Learn anything here from linux, hardware, front-end,
databases, windows, gaming, and more.`
fmt.Println(str)
If we run the code above, we should get an output string as:
welcome to Linuxhint.
Learn anything here from linux, hardware, front-end,
databases, windows, gaming, and more.
NOTE: As mentioned, if you create a string using a raw string literal, you cannot use whitespace characters or include a back-tick character as part of the string.
For example:
fmt.Println(str)
The above code should print:
If you want to use white-space characters in your string, use the double-quoted string as discussed previously.
Interpreted String Literals
The second method you can use to create a mult-line string is interpreted strings. In this case, we use string concatenation using the addition operator (+).
The example below shows how to use interpreted strings.
"welcome to Linuxhint.\n" +
"Learn anything here from linux, hardware, front-end,\n" +
"databases, windows, gaming, and more.\n"
We use double quote and the addition operator to create a multi-line string in this example. This method allows you to include white-space characters.
Conclusion
This guide taught us how to work with strings in the Go programming language. Using this guide, you now know to methods to create multi-line strings.
Stay tuned for more Go tutorials.