In Golang, strings are different from other languages such as Java, C++, Python and more. It's a sequence of variable-width characters where each character is shown by one or more bytes through UTF-8 Encoding. In simple words, strings are the immutable chain of arbitrary bytes involving bytes with zero value or string is a read-only slice of bytes of strings. These can be represented in the Unicode text through UTF-8 encoding. Any operation that appears to 'change' a string makes a new string with the desired customizations. In this blog, we will understand Go strings deeply. So let's begin!
Go strings are a read-only data type that shows a UTF-8 encoded slice of bytes. Like in many other languages, strings in Golang are lines of characters. They are immutable and once a string is created in Golang, its value can't be changed. The attempts at changing it will result in the compiler throwing an error message. Let us look at an example of putting Go strings to use.
package main import "fmt" func main() { // Declare and initialize strings greeting := "Hello" name := "World" // Concatenate strings message := greeting + ", " + name + "!" // Print the result fmt.Println(message) // Get string length fmt.Println("Length of message:", len(message)) } |
Here is an explanation of the example given above-
Now, let us take a look at its output:
Hello, World! Length of message: 13 |
Basically, this example shows string creation, concatenation and length calculation in Go. The strings in Golang are immutable and support UTF-8 encoding by default.
String literal, also called string constant or anonymous string, shows a fixed sequence of characters directly embedded within the source of a program. It's the literal portrayal of a string value. The characteristics of string literals are-
Let us take a look at an example with an explanation, to make things easier for you to understand.
package main import "fmt" func main() { // Double-quoted string literal (interpreted) greeting := "Hello\nWorld"
// Raw string literal (backticks, no interpretation) multiline := `This is a raw string. It can span multiple lines without needing escape sequences.`
// Print them fmt.Println(greeting) fmt.Println(multiline) } package main import "fmt" func main() { // Double-quoted string literal (interpreted) greeting := "Hello\nWorld"
// Raw string literal (backticks, no interpretation) multiline := `This is a raw string. It can span multiple lines without needing escape sequences.`
// Print them fmt.Println(greeting) fmt.Println(multiline) } |
Hello World |
Here is the complete output of the given example:
Hello World This is a raw string. It can span multiple lines without needing escape sequences. |
The string literals in Go are immutable and UTF-8 encoded. Make use of double quotes for simple strings with escapes, use backticks for raw and multi-line content.
Now, let us look at an example of Go strings using double quotes ("") to make things easier for you.
package main import "fmt" func main() { // Double-quoted string literals name := "Yukta" message := "Hello, " + name + "!\nWelcome to Go!" // Print the string fmt.Println(message) } |
Now, let us have a look at the output:
Hello, Yukta! Welcome to Go! |
The double-quoted strings in Golang are interpreted, which means escape sequences like '\n' are processed and they support UTF-8 encoding. The above example shows simple string creation and concatenation through only double quotes.
Now, let us take an example of Go strings using backticks (''), to make it easier for you to understand.
package main import "fmt" func main() { message := `Hello, This is a string using backticks.`
fmt.Println(message) } |
The backticks are put to use to make raw string literals in Go. The raw strings preserve line breaks and special characters as it is written. They do not interpret escape sequences such as \n or \t. They are very much useful for multiline string, writing code snippets and avoiding escape characters.
Read Also: Top 50+ Golang Interview Questions And Answers
As we know, a string is foundationally a sequence of characters used in computing for representing text. Take a look at the important points about String.
So, how do we iterate over a string? Iteration over a string includes accessing every character sequentially. The process for achieving this relies on the programming language being put to use. Now let us take an example on how to iterate over a string, to make it easier for you to understand.
package main import "fmt" func main() { text := "hello" for i, char := range text { fmt.Printf("Index: %d, Character: %c\n", i, char) } } |
Here in this example, the 'range' is used to loop over the string. 'i' is the index of every character starting from 0. Here, 'char' is the rune character at that index, '%c' in 'Printf' prints the character and not the numeric code. It works well even with Unicode characters like emojis or accented letters, as Go handles strings as UTF-8 and 'range' processes them correctly rune by rune.
Accessing individual bytes inside a string relies on the programming language and how strings are managed, such as character encoding. We will take a look at an example on how to access the individual byte of the string in Go.
package main import "fmt" func main() { text := "hello" for i := 0; i < len(text); i++ { fmt.Printf("Index: %d, Byte: %d, Character: %c\n", i, text[i], text[i]) } } |
Here, strings in Golang are preserved as a sequence of bytes encoded by UTF-8. Here, the 'text[i] accesses the i'th byte of the string. The 'len(text)' provides the total number of bytes, '%d' prints the byte value and '%c' prints the character.
This method works perfectly well for ASCII characters, but might break for multi-byte Unicode characters like emojis or accented letters, the ones which should be accessed through range.
Now, you might wonder how one finds the length of the string? So, to find the length of a string, you must use a language-specific function/property like 'len()' in Python, 'strlen()' in C and more. These methods add up the number of characters in the string, excluding any special terminators to return the string's length. Let us look at an example on how to find the length of the string in Go, to make things easier for you to understand.
package main import ( "fmt" ) func main() { text := "hello" length := len(text) fmt.Println("Length in bytes:", length) } |
Here, the 'len(text)' returns the number of bytes in the string. For the simple ASCII strings, bytes = characters, so basically this gives the character count. And for Unicode strings such as emojis or non-english characters, you must use 'utf8.RuneCountInString()' like:
import "unicode/utf8" utf8Length := utf8.RuneCountInString(text) fmt.Println("Length in runes (characters):", utf8Length) |
Operating with strings in Golang is easy yet strong. Whether they are raw strings with backticks, iterating over characters, accessing individual bytes or even measuring string length. Go provides you with the tools to manage both ASCII and Unicode text effectively. Knowing how strings work under the hood assists in writing cleaner and more reliable code. It helps especially while dealing with international characters or performance-critical tasks. So keep practicing and Go will make string handling feel completely naturalistic in no time!
Runes in Go are a data type that stores codes that represent Unicode characters. Basically, Unicode is the collection of all possible characters there in the whole world.
Absolutely yes, Golang has two main kinds of loops which are- for and while.
To check this, the Golang IsNumber() function in the Unicode package is for determining whether a given element r is of datatype rune, which is a numerical value. It checks whether a set of Unicode number characters in category N is valid.
Yes, a string can contain letters, numbers, spaces and special symbols because it is designed to store text data. In Golang, anything written inside quotes is treated as a string including digits and symbols.
Strings are important in Go because they are used to store and process text data such as names, messages and user input. They are widely used in printing output, handling files and working with APIs.
Course Schedule
| Course Name | Batch Type | Details |
| Golang Training | Every Weekday | View Details |
| Golang Training | Every Weekend | View Details |