Junior — Middle
What is the result of the [] operator on a string data type?
sobes.tech AI
Answer from AI
In Go, the [] operator for string data type is used to obtain a byte slice of the string or a single byte by index. A string in Go is an immutable sequence of bytes (UTF-8). When accessing str[i], a byte of type byte (alias for uint8) is returned, not a character in the usual sense, since Unicode characters can occupy multiple bytes.
Example:
s := "Hello"
fmt.Println(s[0]) // Outputs the byte corresponding to the first part of the character 'П'
fmt.Println(string(s[0])) // Outputs an incorrect character, as this is not a complete UTF-8 character
// To get characters (runes), convert the string to a rune slice:
r := []rune(s)
fmt.Println(string(r[0])) // Outputs 'П'
Thus, the [] operator for a string returns a byte at the index, not a Unicode character.