Junior — Middle
What information does the len function return when processing a string?
sobes.tech AI
Answer from AI
In the Go language, the len function when applied to a string returns the number of bytes in that string, not the number of characters (runes).
This is because strings in Go are stored in UTF-8 format, where one character can occupy from 1 to 4 bytes. Therefore, len returns the length in bytes.
Example:
package main
import (
"fmt"
)
func main() {
s := "Привет" // Russian word
fmt.Println(len(s)) // Will output the number of bytes, e.g., 12
}
If you need to get the number of characters (runes), you should convert the string to a slice of runes:
runes := []rune(s)
fmt.Println(len(runes)) // Will output the number of characters, e.g., 6
Thus, len for a string is the length in bytes, not in characters.