Junior
What is the string data type in the Golang language?
sobes.tech AI
Answer from AI
In Golang, a string is an immutable sequence of bytes.
Key features:
- Immutability: Once created, a string cannot be changed. Any operation that modifies a string actually creates a new string.
- Representation: A string contains a sequence of bytes. By default, Golang assumes these bytes represent UTF-8 encoded text.
- Length: The length of a string (
len(s)) returns the number of bytes in the string, not the number of runes (characters). - Indexing: Accessing elements of a string by index (
s[i]) returns the byte at that index. - Runes: To work with characters (runes), iterate over the string using a
for rangeloop, which decodes UTF-8 and provides runes and their indices.
Example:
// Initializing a string
s := "Привет, мир!" // 23 bytes, 12 runes
// Length of the string (in bytes)
byteLength := len(s) // byteLength = 23
// Accessing a byte by index
firstByte := s[0] // firstByte = 208 (byte for 'П' in UTF-8)
// Iterating over runes
runeCount := 0
for index, runeValue := range s {
// index - start index of the rune in bytes
// runeValue - decoded rune
runeCount++
}
// runeCount = 12