Junior
How do strings work in the Go language?
sobes.tech AI
Answer from AI
Strings in Go are immutable sequences of bytes. They are represented as a "byte slice" ([]byte) with a guarantee of immutability.
Key features:
- Immutability: Once created, a string cannot be changed. Any operation that appears to modify a string actually creates a new string.
- Representation: By default, strings in Go represent UTF-8 encoded text. However, they are simply sequences of bytes; interpretation as UTF-8 occurs when working with runes.
- Runes: Unicode characters in Go are represented by the
runetype, which is an alias forint32. Iterating over a string withrangeautomatically decodes UTF-8 and provides runes and their starting byte indices. - Length: The function
len(s)returns the number of bytes in the string, not the number of characters (runes). To get the number of runes, useutf8.RuneCountInString(s)or iterate over the string withrange. - Concatenation: Strings are concatenated using the
+operator. This creates a new string. For efficient concatenation of many strings, it is recommended to usestrings.Builder.
Examples:
// Declaring a string
str := "Hello, 世界"
// Length of the string (in bytes)
byteLen := len(str) // 13 (H(1)e(1)l(1)l(1)o(1),(1) (1)世(3)界(3))
// Iterating over runes
runeCount := 0
for index, runeValue := range str {
// index - starting index of the rune in bytes
// runeValue - the rune
runeCount++
// fmt.Printf("Index: %d, Rune: %c (Value: %d)\n", index, runeValue, runeValue)
}
// runeCount - number of runes (9)
// Accessing a byte by index
// Note: this is a byte, not a character!
// byteAtIndex := str[0] // 'H'
// byteAtIndex := str[7] // Starting byte of the character '世'
// Concatenating strings
newStr := str + "!"
// Using strings.Builder for efficient concatenation
// import "strings"
var builder strings.Builder
builder.WriteString("Hello, ")
builder.WriteString("World")
efficientStr := builder.String() // "Hello, World"