len("oʻzbek") = 7? Byte, rune and UTF-8
A Go string is bytes: len, s[i] and == work on bytes. We compare with JS, Python and PHP, meet runes and fix the Uzbek apostrophe problem.
🌐 Oʻzbekcha · Русский · English
Lesson GO-1.04 · Go: 0 → Guru · ▶️ Watch the video on YouTube · 💻 GitHub
This is the full written version of the video lesson: you can learn from it without watching (or hearing) the video. The video itself is in Uzbek.
What you will learn
A sign-up form allows names of at most 5 characters. React’s <input maxLength={5}> accepts the name “Gʻani”:
"Gʻani".length is 5. The Go backend check len(ism) <= 5 rejects the same name, because for Go its length is 6.
One word shows the same thing: Node says "oʻzbek".length is 6, Go’s len says 7. What is Go counting?
One idea: in Go, text is made of bytes: length, indexing and comparison work byte by byte, and the turned comma
in oʻ takes two bytes.
By the end of the lesson you will be able to:
- explain what
len,s[i]and==count and compare in Go, side by side with JS, Python and PHP; - use
utf8.RuneCountInStringwhen you need the number of characters and[]rune(s)when you need the character itself; - tell from a character’s code point how many bytes it takes in UTF-8;
- bring Uzbek apostrophes in the database and in search to one form without breaking the tutuq belgisi in maʼno.
Today’s three core new words:
| Word | Plain meaning | English term |
|---|---|---|
string = bytes | a Go string is a sequence of bytes: len, indexing s[i] and == work on bytes | string (a sequence of bytes) |
rune | one code point, the Unicode number of a character; another name for int32 | rune |
| UTF-8 | the rule that writes a code point as 1–4 bytes; this is how text in Go source is stored | UTF-8 |
There are also helper words: code point (in the UTF-8 section), the rune slice []rune(s) (in the index
section) and strings.NewReplacer (in the fix section).
Before you start
- GO-X.01 · 20 qatorlik HTTP API: Go’da birinchi xizmat va bitta binary:
go run,fmt.Println, reading a compiler error asfile:line:column. - GO-X.02 · Turlar runtime’da ham bor: “2” + 2 JS’da 22, Go’da kompilyatsiya xatosi: static types,
:=, no implicit conversion, explicit conversionT(x)andfor … range. - GO-X.04 · Nusxa yoki havola? Qiymat semantikasi va pointer: slices (
[]T). This lesson needs only[]rune(s): a list of runes, similar to a JS array. - GO-1.02 · Turlar va overflow: Go rad etadi, x++ esa jim aylanadi: a byte is 8 bits,
uint8holds 0 to 255. - GO-1.03 · Konstanta va iota: JS const emas, time.Sleep(2) va enum oʻrtasidagi jim bug:
time.Duration(for the question below). - GO-1.01 · Go nega bor?
go buildichida nima bor:FROM scratchand time zones (for the last question in “Check yourself”). - You can paste any Go program into go.dev/play and run it. If you downloaded the course code,
open a terminal in the lesson folder (
lessons/004-strings-utf8): every command runs from there. - The comparisons need
node,python3andphp(8.4).tillar/tekshir.shskips whichever is not installed.lexuz/needs internet access.
First, one question from the previous lesson. How long does a Go program wait on this line?
time.Sleep(2)A) 2 seconds · B) 2 milliseconds · C) 2 nanoseconds
Answer
C: 2 nanoseconds. 2 is an untyped constant, so it takes the type of the Sleep parameter, time.Duration.
And Duration counts nanoseconds. “2 seconds” is Python’s time.sleep rule, “2 milliseconds” is the rule of JS
setTimeout. For two seconds you write 2 * time.Second.
Today’s question is also about a unit: len returned 7 — seven of what?
One word, four languages
Go first, hook/main.go:
package main
import "fmt"
func main() {
fmt.Println(len("oʻzbek")) // JS: "oʻzbek".length → 6
}Line 6 has len("oʻzbek"), the length of the string; the comment shows the JS result. Let’s run both languages side
by side:
$ node -p '"oʻzbek".length'
6
$ go run hook/main.go
7Two more languages, Python and PHP:
$ python3 -c 'print(len("oʻzbek"))'
6
$ php -r 'echo strlen("oʻzbek");'
7
$ php -r 'echo mb_strlen("oʻzbek");'
6tillar/tekshir.sh calls all four with one command:
$ ./tillar/tekshir.sh
js .length 6
python len 6
php strlen 7
go len 7One word gave two different numbers, because the languages count three different units:
| Language | Expression | "oʻzbek" | What it counts |
|---|---|---|---|
| JavaScript / TS | s.length | 6 | UTF-16 units |
| Python | len(s) | 6 | code points (in Go: runes) |
| PHP | strlen($s) | 7 | bytes |
| PHP | mb_strlen($s) | 6 | characters (code points) |
| Go | len(s) | 7 | bytes |
In Go a string is a sequence of bytes, and len counts those bytes, like PHP’s strlen. The Go specification
says exactly this: “The number of bytes is called the length of the string”. The unit Python counts is called a
rune in Go. JavaScript uses a third kind: UTF-16 units (ECMAScript: the length of a string is the number of
16-bit elements). For this word JS and Python both gave 6, but they do not always agree: you will see this in the
mid-lesson question.
UTF-8: code point → 1–4 bytes
Why exactly 7 bytes? In JavaScript, codePointAt returns the number of a character:
$ node -p '"oʻzbek".codePointAt(1)'
699(This command is not a file in the course folder; the code is in the command itself.) This number is called a
code point: the Unicode number of a character. It is usually written in hexadecimal (hex) as U+02BB:
0x2BB = 699.
UTF-8 is the rule that writes a code point as bytes. A small code point takes one byte, a larger one takes two, three or four bytes (RFC 3629):
| Code point | Bytes | Example |
|---|---|---|
| 0 … 127 | 1 | o = 111, z = 122 |
| 128 … 2 047 | 2 | ʻ = 699 |
| 2 048 … 65 535 | 3 | |
| 65 536 … 1 114 111 | 4 |
The first row is the ASCII range: Latin letters, digits and keyboard characters take one byte each. The turned comma
in oʻ is 699, so it takes two bytes. This is how "oʻzbek" sits in a Go string:
| Character | o | ʻ | z | b | e | k |
|---|---|---|---|---|---|---|
| Code point | U+006F | U+02BB | U+007A | U+0062 | U+0065 | U+006B |
| UTF-8 bytes (hex) | 6f | ca bb | 7a | 62 | 65 | 6b |
| Number of bytes | 1 | 2 | 1 | 1 | 1 | 1 |
7 bytes in total, and Go’s len counts exactly these. In hexadecimal, ca = 12 × 16 + 10 = 202 and bb = 187.
A Go string can hold any bytes. But Go source code itself is written in UTF-8 (spec: “Source code is Unicode text
encoded in UTF-8”), so the quoted "oʻzbek" becomes exactly these 7 bytes.
Rune: the unit Python counts
The six things Python counted are these code points: o, ʻ, z, b, e and k. In Go the type of one code point is
rune. It is another name for int32 (spec: “rune alias for int32”). And byte is another name for uint8.
But a rune is not a letter either. In the alphabet oʻ is one letter, but it is two runes: o and ʻ.
| What we count | How many | Which |
|---|---|---|
| letters (alphabet) | 5 | oʻ, z, b, e, k |
| runes (code points) | 6 | o, ʻ, z, b, e, k |
| bytes (UTF-8) | 7 | 6f, ca, bb, 7a, 62, 65, 6b |
Go can count both, uzunlik/main.go (uzunlik means “length”):
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "oʻzbek"
fmt.Println(len(s)) // baytlar soni
fmt.Println(utf8.RuneCountInString(s)) // rune'lar (belgilar) soni
}| Line | Code | What it does |
|---|---|---|
| 3–6 | import ( "fmt" "unicode/utf8" ) | unicode/utf8 is the standard package for working with UTF-8 |
| 9 | s := "oʻzbek" | a 7-byte string |
| 10 | len(s) | the number of bytes |
| 11 | utf8.RuneCountInString(s) | the number of runes: reads the bytes by the UTF-8 rule and counts code points |
$ go run uzunlik/main.go
7
6Seven and six. In JavaScript, spread counts code points: [...s] spreads the string into an array of code points.
$ node -p '[..."oʻzbek"].length'
6(This command is not in the folder either.)
Index: s[1] is a byte, not a character
In JavaScript and Python, s[1] gives the second character:
$ node -p '"oʻzbek"[1]'
ʻ
$ python3 -c 'print("oʻzbek"[1])'
ʻWhat does the same expression print in Go?
s := "oʻzbek"
fmt.Println(s[1])A) ʻ · B) 202 · C) o
Answer
B: 202. Indexing a Go string gives one byte, of type byte (spec: “a[x] is the non-constant byte value at
index x and the type of a[x] is byte”). The byte at index 1 is the first byte of the turned comma, ca, which is 202
in decimal. fmt.Println prints a byte as a number. If you chose “ʻ”, you carried over the JS and Python habit.
If you chose “o”, you thought indexing starts at 1: in Go it starts at 0 too.
The full program, indeks/main.go:
package main
import "fmt"
func main() {
s := "oʻzbek"
fmt.Println(s[1]) // JS va Python'da s[1] → "ʻ"; Go'da: 1-oʻrindagi bayt (byte, son)
fmt.Printf("%x\n", s[1]) // oʻsha bayt oʻn oltilikda: ca (ʻ ning birinchi bayti)
fmt.Println(string([]rune(s)[1])) // rune'lar boʻyicha: 1-element — ʻ
}| Line | Code | What it does |
|---|---|---|
| 7 | s[1] | the byte at index 1; its type is byte (uint8), Println prints it as a number |
| 8 | fmt.Printf("%x\n", s[1]) | the same byte in hexadecimal: %x is hex, \n is a new line |
| 9 | []rune(s) | converts the string to a rune slice (conversion T(x)): a list similar to a JS array, each element one code point |
| 9 | []rune(s)[1] | the element of that list at index 1: ʻ (699) |
| 9 | string(…) | turns the rune back into a string, so Println prints the character, not the number |
$ go run indeks/main.go
202
ca
ʻThe difference: a string index walks over bytes, a rune slice index walks over code points.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
s[i] (byte, hex) | 6f | ca | bb | 7a | 62 | 65 | 6b |
[]rune(s)[i] (rune) | o | ʻ | z | b | e | k | — |
In JavaScript, TextEncoder gives you the bytes. Its element at index 1 is 202 as well:
$ node -p 'new TextEncoder().encode("oʻzbek")[1]'
202(Not in the folder.) Note: []rune(s) creates a new slice with a copy of the whole text. For a short name or a title
that is no problem; for a large text it is expensive.
Mid-lesson question: emoji
In JavaScript the length of this emoji is 2:
$ node -p '"😀".length'
2😀 = U+1F600 = 128 512. Compare the code point with the UTF-8 table. What is len("😀") in Go?
A) 1 · B) 2 · C) 4
Answer
C: 4. 128 512 > 65 535, so it is the last row of the table: UTF-8 writes it as four bytes. It is one rune.
If you chose “2”, you copied the JS result. The 2 in JS has a different cause: UTF-16 splits a character above
65 535 into two 16-bit units (a surrogate pair). “1” is the rune count, not len.
emoji/main.go:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "😀" // U+1F600 = 128512 > 65535
fmt.Println(len(s)) // baytlar
fmt.Println(utf8.RuneCountInString(s)) // rune'lar
}$ go run emoji/main.go
4
1Now the full table (the Python and PHP results come from the same machine):
| Language | Expression | "oʻzbek" | "😀" | What it counts |
|---|---|---|---|---|
| JavaScript / TS | s.length | 6 | 2 | UTF-16 units |
| JavaScript | [...s].length | 6 | 1 | code points |
| Python | len(s) | 6 | 1 | code points |
| PHP | strlen($s) · mb_strlen($s) | 7 · 6 | 4 · 1 | bytes · characters |
| Go | len(s) | 7 | 4 | bytes |
| Go | utf8.RuneCountInString(s) | 6 | 1 | runes (code points) |
For Uzbek names, JS .length and the Go rune count agree. For emoji they differ: in JS, [...s].length counts code
points.
One word, four apostrophes
Now a problem specific to Uzbek text. The turned comma ʻ is not on an ordinary keyboard, so one word gets written
in four ways:
| Mark | Name | Code point |
|---|---|---|
' | keyboard apostrophe | U+0027 = 39 |
ʻ | turned comma | U+02BB = 699 |
’ | right curly apostrophe | U+2019 = 8217 |
‘ | left curly apostrophe | U+2018 = 8216 |
Unicode’s locale data (CLDR, uz.xml) lists oʻ and gʻ with the turned comma in the Uzbek alphabet.
tort/main.go (tort means “four”) prints len for all four spellings. Compare the code points with the UTF-8
table: which row is right?
A) 6 · 7 · 8 · 8 · B) 7 · 7 · 7 · 7 · C) 6 · 7 · 7 · 7
Answer
A: 6 · 7 · 8 · 8. The keyboard apostrophe (39) is 1 byte, the turned comma (699) is 2 bytes. The curly apostrophes have code points above 2 047, so they take three bytes each. The rune count is 6 in all four: only the bytes differ. If you chose “B”, you thought that text that looks the same has the same bytes. If you chose “C”, you thought every apostrophe takes 2 bytes, like the turned comma.
package main
import (
"fmt"
"unicode/utf8"
)
// Bitta soʻz, toʻrt xil apostrof. Koʻzga deyarli bir xil, baytlari har xil.
func main() {
sozlar := []string{
"o'zbek", // U+0027 APOSTROPHE (klaviaturadagi)
"oʻzbek", // U+02BB MODIFIER LETTER TURNED COMMA (teskari vergul, toʻgʻrisi)
"o’zbek", // U+2019 RIGHT SINGLE QUOTATION MARK (oʻng jingalak)
"o‘zbek", // U+2018 LEFT SINGLE QUOTATION MARK (chap jingalak)
}
for _, s := range sozlar {
fmt.Printf("%s len=%d rune=%d\n", s, len(s), utf8.RuneCountInString(s))
}
}| Line | Code | What it does |
|---|---|---|
| 10–15 | sozlar := []string{…} | a slice of four strings (sozlar means “words”); the comments give each apostrophe’s code point |
| 16 | for _, s := range sozlar | a loop over each element; _ means the index is not needed |
| 17 | fmt.Printf("%s len=%d rune=%d\n", …) | %s is a string, %d an integer |
$ go run tort/main.go
o'zbek len=6 rune=6
oʻzbek len=7 rune=6
o’zbek len=8 rune=6
o‘zbek len=8 rune=6On screen all four look almost the same. For Go they are four different byte sequences.
On a real site: lex.uz
This is not theory. While preparing the lesson we downloaded one law page on lex.uz (OʻRQ-1184). lexuz/main.go
counts the marks after o/g in the visible text of the page (menus included). It removes <head>, <script>,
<style> and the tags. It needs internet access:
$ curl -sL https://lex.uz/uz/docs/8548754 | go run ./lexuz
U+02BB 50
U+2018 13
U+2019 1
lotin+kirill: "pе" (U+0435)Most are turned commas (50), but there is also the left curly apostrophe (13) and the right curly apostrophe (1).
Even one line mixes two marks: the page header “Oʻzbekiston Respublikasining Qonuni, 21.10.2026 yildagi
O‘RQ-1184-son” (ʻ and ‘). Most of the left curly apostrophes are in the site menus; the right curly apostrophe is
on the language switch button (O’zb). The last line is a Cyrillic е (U+0435) inside a Latin word, which is
outside today’s topic (kirill/ in the README appendix). If the site changes, the numbers can change too: these are
the results of 2026-11-26.
The backend consequence: == gives false
The database stores Oʻzbekiston with the turned comma. A user typed O'zbekiston into search with the keyboard
apostrophe. teng/main.go (teng means “equal”; saytda is “from the site’s list”, qidiruv is “from the search
field”):
package main
import "fmt"
func main() {
saytda := "Oʻzbekiston" // saytdagi roʻyxatda: ʻ (U+02BB)
qidiruv := "O'zbekiston" // foydalanuvchi klaviaturadan yozdi: ' (U+0027)
fmt.Println(saytda == qidiruv)
}$ go run teng/main.go
falseGo compares strings byte by byte (spec: Comparison operators). Oʻzbekiston is 12 bytes, O'zbekiston is 11 bytes:
the bytes differ, so false. JavaScript’s strict equality === also gives false. Unicode normalization
(normalize("NFC") or "NFKC") does not help either: these are different characters, not two spellings of one
character.
$ node -p '"Oʻzbekiston" === "O\x27zbekiston"'
false
$ node -p '["NFC", "NFKC"].map(f => "Oʻzbekiston".normalize(f) === "O\x27zbekiston".normalize(f))'
[ false, false ](Neither command is in the folder. \x27 is the keyboard apostrophe, written this way so it does not clash with the
shell quotes.)
The fix: only the apostrophe after o and g
The first idea is to replace every ' with ʻ. tuzat/main.go (tuzat means “fix”):
package main
import (
"fmt"
"strings"
)
func main() {
saytda := "Oʻzbekiston"
qidiruv := "O'zbekiston"
qidiruv = strings.ReplaceAll(qidiruv, "'", "ʻ") // har bir ' (U+0027) ni ʻ (U+02BB) ga almashtir
fmt.Println(saytda == qidiruv)
fmt.Println(strings.ReplaceAll("ma'no", "'", "ʻ")) // cheklov: toʻgʻrisi maʼno (ʼ U+02BC, tutuq belgisi)
}On line 11, strings.ReplaceAll(qidiruv, "'", "ʻ") replaces every ' in the text with ʻ. Line 13 does the same
replacement in the word maʼno.
$ go run tuzat/main.go
true
maʻnoSearch works, but maʼno is broken. The mark in that word is not the turned comma but the tutuq belgisi ʼ
(U+02BC, the glottal-stop sign): CLDR lists it separately. So we replace only the apostrophes after o and g,
curly ones included, with the turned comma. normal/main.go:
package main
import (
"fmt"
"strings"
)
func main() {
saytda := "Oʻzbekiston"
qidiruv := "O'zbekiston"
// Faqat o/g dan keyingi apostrof (klaviatura ' va egri ’ ‘) → ʻ (U+02BB). Boshqa joydagi ' tegilmaydi:
// maʼno dagi tutuq belgisi (ʼ U+02BC) teskari vergul emas. Toʻliqroq qoida va chegaralar: ../tozala/
r := strings.NewReplacer(
"o'", "oʻ", "g'", "gʻ", "O'", "Oʻ", "G'", "Gʻ",
"o’", "oʻ", "g’", "gʻ", "O’", "Oʻ", "G’", "Gʻ",
"o‘", "oʻ", "g‘", "gʻ", "O‘", "Oʻ", "G‘", "Gʻ",
)
fmt.Println(r.Replace(qidiruv) == saytda)
fmt.Println(r.Replace("ma'no"))
// egri apostroflar ham: true true
fmt.Println(r.Replace("O’zbekiston") == saytda, r.Replace("O‘zbekiston") == saytda)
}| Line | Code | What it does |
|---|---|---|
| 13 | strings.NewReplacer(…) | a replacer from the strings package: its arguments are “old, new” pairs |
| 14 | "o'", "oʻ", … | keyboard apostrophe: after o, g, O, G it becomes ʻ |
| 15–16 | "o’", "oʻ", … · "o‘", "oʻ", … | the same for the right and left curly apostrophes |
| 18 | r.Replace(qidiruv) == saytda | Replace replaces all pairs in one pass over the text, then we compare |
| 19 | r.Replace("ma'no") | an apostrophe after a is not in the pairs: it stays in place |
| 21 | two == | the curly-apostrophe spellings also become equal to saytda |
$ go run normal/main.go
true
ma'no
true truetrue, and maʼno is untouched. strings.NewReplacer performs the replacements in the order they appear in the
text, without overlapping matches (pkg.go.dev).
The rule: put this replacement in one function and call it both before saving and before searching. Then the
text in the database and in search is made of the same bytes. A fuller rule is in tozala/ in the course folder:
ʻ after o/g, ʼ between other letters. It has a limit too: Go'da → Goʻda (README appendix).
Going deeper (optional): inside UTF-8 and slicing by bytes
How ʻ becomes ca bb
In a multi-byte character every byte starts with a prefix. The first byte and the continuation bytes have different
prefixes. bitlar/main.go (bitlar means “bits”):
package main
import "fmt"
func main() {
r := 'ʻ'
fmt.Printf("%U = %d = %b (%d bit)\n", r, r, r, len(fmt.Sprintf("%b", r)))
b := []byte(string(r))
// 2 baytli qolip: 110xxxxx 10xxxxxx, 11 ta x ga raqamning bitlari
fmt.Printf("110|%05b 10|%06b = % x\n", r>>6, r&0x3f, b)
}| Line | Code | What it does |
|---|---|---|
| 6 | r := 'ʻ' | a rune literal (in single quotes): type rune, value 699 |
| 7 | %U, %d, %b | the U+02BB form, decimal and binary; len(fmt.Sprintf("%b", r)) is the number of bits in the binary form |
| 8 | []byte(string(r)) | rune → string → byte slice: the character’s UTF-8 bytes |
| 10 | r>>6, r&0x3f | >>6 drops the last 6 bits (the high bits remain), &0x3f keeps only the last 6 bits (0x3f = 111111) |
| 10 | %05b, %06b, % x | binary with 5 and 6 digits; bytes in hex separated by spaces |
$ go run bitlar/main.go
U+02BB = 699 = 1010111011 (10 bit)
110|01010 10|111011 = ca bb699 in binary is 10 bits. The two-byte template has 11 free places (x), so one 0 is added in front:
01010111011.
| 1st byte | 2nd byte | |
|---|---|---|
| Template | 110xxxxx | 10xxxxxx |
| Bits of 699 | 01010 | 111011 |
| Result | 11001010 = ca | 10111011 = bb |
The bits a byte starts with tell its role:
| Byte starts with | Meaning |
|---|---|
0xxxxxxx | a 1-byte character (ASCII) |
110xxxxx | the start of a 2-byte character |
1110xxxx | the start of a 3-byte character |
11110xxx | the start of a 4-byte character |
10xxxxxx | a continuation byte |
Thanks to these prefixes, a program can find the start of a character from any UTF-8 byte: it skips backwards over
bytes that start with 10 (RFC 3629 §3).
Slicing by bytes
In JavaScript, slice(0, 2) takes two UTF-16 units, that is oʻ:
$ node -p '"oʻzbek".slice(0, 2)'
oʻ(Not in the folder.) In Go, s[:2] is the bytes from 0 to 2 (2 not included): o and half of the turned comma.
This is called slicing. kesish/main.go (kesish means “cutting”):
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "oʻzbek"
fmt.Printf("%q\n", s[:2]) // 2 bayt: belgining yarmi
fmt.Println(utf8.ValidString(s[:2])) // bu UTF-8 emas
fmt.Printf("%q\n", string([]rune(s)[:2])) // 2 rune: butun "oʻ"
fmt.Printf("%q\n", string([]rune(s)[:1])) // 1 rune: faqat "o"
}| Line | Code | What it does |
|---|---|---|
| 10 | s[:2] | the first 2 bytes; %q prints the value in quotes and shows a broken byte as \xca |
| 11 | utf8.ValidString(s[:2]) | are these bytes valid UTF-8? |
| 12 | string([]rune(s)[:2]) | the first 2 runes: the whole oʻ |
| 13 | string([]rune(s)[:1]) | the first 1 rune: only o |
$ go run kesish/main.go
"o\xca"
false
"oʻ"
"o"s[:2] cut the character in half: ca stayed, bb did not, and these bytes are no longer valid UTF-8. In an app
such a byte usually shows up as �. Slicing through a rune slice keeps the whole character. But it can still break
a letter: in the last line only o is left of oʻ, because oʻ is two runes.
Common mistakes
1. Thinking len is the number of characters. This is the classic mistake of this topic. If a limit on a name,
title or SMS is checked with len(s) <= n, every ʻ is counted twice: “Gʻani”, accepted by the frontend, is 6 on
the backend. There is no error message; the result is silently wrong. The example is in the sections “One word,
four languages” and “Rune”. Fix: for a character limit use utf8.RuneCountInString(s).
2. Thinking s[i] is a character. If you follow the JS habit and store the index result in a rune variable,
Go refuses. This program is not in the course folder; save it as xato/main.go and run it:
package main
import "fmt"
func main() {
s := "oʻzbek"
var c rune = s[1] // JS kabi belgi kutyapmiz
fmt.Println(string(c))
}$ go run xato/main.go
# command-line-arguments
xato/main.go:7:15: cannot use s[1] (value of type byte) as rune value in variable declarationxato/main.go:7:15 is line 7, column 15, that is s[1]. cannot use s[1] (value of type byte) as rune value in
variable declaration means “you cannot use s[1], of type byte, as a rune value in a variable declaration”. Go
does no implicit conversion. If you write rune(s[1]), it compiles, but it is still byte 202:
string(rune(s[1])) → Ê. Fix: []rune(s)[1], or string([]rune(s)[1]) if you need the character as a
string. Details in the “Index” section.
3. Slicing by bytes. s[:n] takes n bytes and can cut an Uzbek letter in half: "o\xca". In a
notification or a preview text it shows up as �. The example is in the “Going deeper” section. Fix:
string([]rune(s)[:n]).
4. Comparing text that looks the same with ==. Oʻzbekiston and O'zbekiston are not equal, and
normalization does not help. The example is in the section “The backend consequence”. Fix: replace the
apostrophes after o/g with strings.NewReplacer both before saving and before searching. Do not replace every
': strings.ReplaceAll turns maʼno into maʻno.
Check yourself
Answer first, then open the answer.
1. Why is len("oʻzbek") 7 in Go but 6 in Python?
Answer
Go’s len counts bytes, and the turned comma takes two bytes in UTF-8. Python counts code points, which Go calls
runes: there are 6.
2. What does s[1] return in Go? And if you need the character?
Answer
One byte, of type byte (202 for "oʻzbek"). For the character, convert the string to a rune slice: []rune(s)[1],
or string([]rune(s)[1]) as a string.
3. What does this line print?
fmt.Println(len("gʻoz"))A) 3 · B) 4 · C) 5
Answer
C: 5. g is 1 byte, ʻ is 2 bytes, o and z one each. There are 4 runes and 3 letters (gʻ, o, z). In the
course folder, sinov/main.go:
package main
import "fmt"
func main() {
fmt.Println(len("gʻoz")) // g 1 + ʻ 2 + o 1 + z 1
}$ go run sinov/main.go
54. Both spellings use a curly apostrophe, and both are 8 bytes. What does this program print? (It is not in the
course folder: save it as egri/main.go.)
package main
import "fmt"
func main() {
a := "o’zbek" // ’ U+2019
b := "o‘zbek" // ‘ U+2018
fmt.Println(len(a) == len(b), a == b)
}A) true true · B) true false · C) false false
Answer
B: true false. The lengths are equal: both ’ and ‘ take 3 bytes. But the bytes differ: ’ = e2 80 99,
‘ = e2 80 98. == compares bytes, not lengths.
$ go run egri/main.go
true false5. From GO-1.01: in a FROM scratch image the program fails with unknown time zone. What do
you do?
Answer
import _ "time/tzdata" adds the time-zone database to the binary. Or you use a distroless image that contains the
time-zone database.
Homework
Starter files and answers are in the lesson folder on GitHub:
lessons/004-strings-utf8
(the uyga/ folder). Run the commands from the lesson folder.
🟢 Easy (uyga/oson/main.go): a sign-up form. The frontend’s <input maxLength={5}> accepts “Gʻani”, but
ismTekshir (“check name”) in Go says “juda uzun” (“too long”). Before running it, write down the result for
each name. Then fix the backend so that it counts the same way as the frontend.
package main
import "fmt"
// 🟢 Oson: roʻyxatdan oʻtish formasi.
// Frontend'da <input maxLength={5}>: React "Gʻani" ni oʻtkazadi ("Gʻani".length === 5).
// Backend esa xuddi shu ismni "juda uzun" deb rad etadi.
// 1) Ishga tushirishdan OLDIN yozing: har bir ism uchun nima chiqadi?
// 2) Nega "Gʻani" rad etildi? Tuzating, toki backend frontend bilan bir xil sanasin.
func ismTekshir(ism string) string {
if len(ism) <= 5 {
return "qabul"
}
return "juda uzun"
}
func main() {
for _, ism := range []string{"Anvar", "Gʻani", "Oʻktam"} {
fmt.Println(ism, ismTekshir(ism))
}
}🟡 Medium (uyga/orta/main.go): qisqa(s, n) (“short”) for a notification (push, Telegram) must return the
first n characters of the text and add … if it was cut. Right now it cuts by bytes:
package main
import "fmt"
// 🟡 Oʻrta: bildirishnoma (push, Telegram) uchun matnning qisqa koʻrinishi.
// qisqa(s, n) matnning birinchi n ta belgisini qaytarishi va kesilgan boʻlsa oxiriga "…" qoʻshishi kerak.
// Hozirgi kod baytlab kesadi: oʻzbekcha matnda belgi yarmidan kesiladi va ilovada "�" chiqadi.
// Tuzating: kesish belgilar (rune'lar) boʻyicha boʻlsin. %q buzilgan baytni \xca kabi koʻrsatadi.
func qisqa(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}
func main() {
fmt.Printf("%q\n", qisqa("Toʻlov qabul qilindi", 3)) // kutilgan: "Toʻ…"
fmt.Printf("%q\n", qisqa("Gʻalaba", 7)) // kutilgan: "Gʻalaba"
fmt.Printf("%q\n", qisqa("Payme orqali toʻlov", 5)) // kutilgan: "Payme…"
}$ go run uyga/orta/main.go
"To\xca…"
"Gʻalab…"
"Payme…"Make it cut by runes: the output should be "Toʻ…", "Gʻalaba", "Payme…".
Extra exercises remain from the first version of the lesson (homework/ ):
- 🟢 Easy: how many bytes and how many runes are in your name?
- 🟡 Medium: count the letters in an Uzbek word:
oʻ,gʻ,sh,chare one letter each. - 🟠 Hard: reverse a word by runes and try it on
oʻzbek: which letter did the apostrophe stick to? - 🔴 Guru: sort words in Uzbek alphabetical order (
oʻ gʻ sh chafter z).
Answers: uyga/javob/ and homework/README.md . Try it yourself first.
Answer
🟢 len("Gʻani") = 6, because ʻ is two bytes; the rune count is 5. The check should be
utf8.RuneCountInString(ism) <= 5. “Oʻktam” is 6 characters on the frontend too, so both sides reject it.
package main
import (
"fmt"
"unicode/utf8"
)
// Javob: len baytlarni sanaydi: "Gʻani" = 6 bayt (ʻ ikki bayt), lekin 5 rune.
// Frontend'dagi .length UTF-16 birliklarini sanaydi; bu ismlarda u rune soniga teng, shuning uchun backend
// rune'larni sanashi kerak: utf8.RuneCountInString.
// (Emoji kabi U+FFFF dan katta belgilarda JS .length 2 beradi, rune esa 1 — bu yerda ular uchramaydi.)
func ismTekshir(ism string) string {
if utf8.RuneCountInString(ism) <= 5 {
return "qabul"
}
return "juda uzun"
}
func main() {
for _, ism := range []string{"Anvar", "Gʻani", "Oʻktam"} {
fmt.Println(ism, ismTekshir(ism))
}
}$ go run uyga/javob/oson/main.go
Anvar qabul
Gʻani qabul
Oʻktam juda uzunFor characters above U+FFFF, such as emoji, JS .length gives 2 while the rune count is 1. For such names use
[...s].length on the frontend.
🟡 s[:n] takes n bytes: the 3rd byte of “Toʻlov” is the first byte of the turned comma (ca). []rune(s) splits
the text into runes, so the cut now happens on whole characters:
package main
import "fmt"
// Javob: s[:n] n ta BAYT oladi: "Toʻlov" ning 3-bayti ʻ ning birinchi bayti (ca), shuning uchun "To\xca…".
// []rune(s) matnni rune'larga ajratadi: kesish endi butun belgilar boʻyicha.
// Eslatma: rune ham har doim "harf" emas (oʻ = o + ʻ ikki rune), lekin UTF-8 endi buzilmaydi.
func qisqa(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
func main() {
fmt.Printf("%q\n", qisqa("Toʻlov qabul qilindi", 3))
fmt.Printf("%q\n", qisqa("Gʻalaba", 7))
fmt.Printf("%q\n", qisqa("Payme orqali toʻlov", 5))
}$ go run uyga/javob/orta/main.go
"Toʻ…"
"Gʻalaba"
"Payme…"Extra exercises (details in homework/README.md):
- 🟢
lencounts bytes,utf8.RuneCountInStringcounts runes: “Gʻayrat” is 8 bytes and 7 runes. - 🟡 Walk over the runes and treat the pairs
oʻ gʻ sh chas one letter:shaharis 6 runes, 5 letters. - 🟠
oʻzbekreversed iskebzʻo: the turned comma now sticks toz, becauseoʻis one letter but two runes. - 🔴 Go sorts strings byte by byte, so
oʻriklands betweenolmaandpomidor. The alphabet order has to be written by hand:golang.org/x/text/collatev0.42.0 does not apply this rule.
Sources
- The Go specification: String types (string = bytes,
len= bytes), Index expressions (s[i]= a byte), Numeric types (rune=int32,byte=uint8), Comparison operators , Source code representation unicode/utf8(RuneCountInString,ValidString),strings.NewReplacer,strings.ReplaceAll- Rob Pike, Strings, bytes, runes and characters in Go (Go blog): https://go.dev/blog/strings
- JavaScript: ECMAScript String type
(16-bit elements) · Python: str — code points
· PHP:
strlen(bytes) - RFC 3629: UTF-8
- Unicode CLDR:
common/main/uz.xml({oʻ} {gʻ}= U+02BB,ʼ= U+02BC) - lex.uz: OʻRQ-1184 (counted on 2026-11-26)
- Course folder and README: lessons/004-strings-utf8
- All results from
go1.26.8 linux/amd64, Node v24.10.0, Python 3.13.15 and PHP 8.4.26, 2026-11-26.
Video and code
💻 Code and homework answers on GitHub
← Previous lesson: GO-1.03 · Next lesson: GO-1.05 → · All lessons
comments