Senior
What is a string in Go? How to find out the length of a string in characters and in bytes?
sobes.tech AI
Answer from AI
In Go, a string (string) is an immutable sequence of bytes, usually containing text in UTF-8 encoding.
- The length of a string in bytes is simply the number of bytes in the
[]byteslice underlying the string. - The length of a string in characters (runes) is the number of Unicode characters, which can occupy different numbers of bytes.
Example:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "Привет"
fmt.Println("Length in bytes:", len(s))
fmt.Println("Length in characters:", utf8.RuneCountInString(s))
}
The output will be approximately:
Length in bytes: 12
Length in characters: 6
Because each Russian character in UTF-8 takes 2 bytes.