Here are the common ways to grab “the first 2 characters” in Go, depending on what you really mean by “character.”
1. First 2 bytes
If you’re 100 % sure the string is ASCII-only (e.g. IDs, English text, hex digits, …), each character is exactly one byte, so a simple slice works:
s := "Hello"
first2 := s[:2] // "He"
fmt.Println(first2)
⚠️ Panics if len(s) < 2 (run‐time “slice bounds out of range”).
2. First 2 runes (Unicode code points)
Most real-world strings are UTF-8. A single “character” (rune) can be 1–4 bytes. Slicing by bytes might split a multibyte rune and give you invalid UTF-8. Grab the first two runes instead:
A. Convert to []rune (quick & easy, allocates)
s := "世界 means world"
r := []rune(s) // UTF-8 → UTF-32 copy
if len(r) >= 2 {
first2 := string(r[:2]) // "世界"
fmt.Println(first2)
}
B. No heap allocation (iterate indices)
func firstNRunes(s string, n int) string {
if n <= 0 { return "" }
runeCount := 0
for i := range s { // i = byte index of each rune
if runeCount == n { // reached desired count
return s[:i] // slice using byte offset
}
runeCount++
}
return s // string shorter than n runes, return whole thing
}
s := "世界 means world"
fmt.Println(firstNRunes(s, 2)) // "世界"
• Zero allocations.
• Works even if the string has fewer than n runes (returns the whole string).
Cheat-sheet
| Need | Code | Notes |
|---|
| First 2 bytes | s[:2] | ASCII-only, string length ≥ 2 |
| First 2 runes (allocates) | string([]rune(s)[:2]) | Simple, but copies whole string |
| First 2 runes (no alloc) | function with for i := range s { … } | Efficient for hot paths |
Quick utility function
// FirstN returns the first n runes of s (or the whole string if shorter).
func FirstN(s string, n int) string {
if n <= 0 {
return ""
}
i := 0
for idx := range s {
if i == n {
return s[:idx]
}
i++
}
return s
}
Usage:
fmt.Println(FirstN("こんにちは", 2)) // "こん"
fmt.Println(FirstN("Hi", 2)) // "Hi"
Happy Go-coding! 🏃♂️💨