Sobes.tech
Junior — Middle

How is access to a string character by its position performed, and what should be considered when using this approach?

sobes.tech AI

Answer from AI

In Go, access to a character in a string by position is done through indexing, for example s[i], where s is a string and i is the position.

However, it is important to remember that strings in Go are sequences of bytes in UTF-8 encoding. When indexing, you get a byte, not a rune (character). If the string contains only ASCII characters, this is not a problem, but for Unicode characters that occupy multiple bytes, such access can lead to incorrect results.

To get a rune (character) by position, you need to convert the string to a slice of runes:

s := "Привет"
runes := []rune(s)
fmt.Println(string(runes[0])) // Will output 'П'

Thus, when working with character positions in a string, it is important to remember that byte indexing does not always correspond to characters, especially for Unicode.

How is access to a string character by its position… - sobes.tech