Golang / GoLang Basics Interview Questions
How does Go handle strings, runes, and bytes? Why is len(s) not the character count?
Go strings are immutable sequences of bytes stored in UTF-8 encoding. Since UTF-8 is a variable-width encoding, a single character (rune) can occupy 1 to 4 bytes. This means len(s) reports bytes, not characters — a fact that trips up many beginners.
s := "Hello, ä¸ç" // UTF-8 string containing ASCII + Chinese chars // len() counts BYTES fmt.Println(len(s)) // 13 // 7 ASCII (1 byte each) + 2 Chinese (3 bytes each) = 13 // Count RUNES (Unicode characters) fmt.Println(utf8.RuneCountInString(s)) // 9 fmt.Println(len([]rune(s))) // 9 (same) // Byte-by-byte iteration â WRONG for multi-byte chars for i := 0; i < len(s); i++ { fmt.Printf("%d:%x ", i, s[i]) // raw byte values } // Rune-by-rune iteration â CORRECT for Unicode // range decodes UTF-8 runes automatically for i, r := range s { // i = byte offset, r = rune (Unicode code point) fmt.Printf("%d:%c ", i, r) } // Conversions b := []byte(s) // string â []byte (copies) r := []rune(s) // string â []rune (copies) s2 := string(b) // []byte â string s3 := string(r) // []rune â string // Efficient string building (avoid + in loops) var sb strings.Builder for _, word := range []string{"Go", " ", "rocks"} { sb.WriteString(word) } fmt.Println(sb.String()) // Go rocks
More Related questions...