Sobes.tech
Junior — Middle

What is the result returned by the built-in function len when called on a string?

sobes.tech AI

Answer from AI

In Go, the built-in len function, when called on a string, returns the number of bytes in that string, not the number of characters (runes).

This is because strings in Go are sequences of bytes in UTF-8 encoding. If the string contains only ASCII characters, the number of bytes equals the number of characters. But if the string contains multibyte characters (for example, Cyrillic, emojis), then len will return the total number of bytes, not the number of characters.

Example:

s := "Привет"
fmt.Println(len(s)) // Will output the number of bytes, e.g., 12

runes := []rune(s)
fmt.Println(len(runes)) // Will output the number of characters, e.g., 6

To get the number of characters (runes), you should convert the string to a slice of runes and take its length.