หัวข้อสำคัญของ Go
Go Runes, Bytes and strings.Builder
Why len("héllo") is 6, how to work with characters, and how to build long strings fast.
สิ่งที่คุณจะได้เรียนรู้
- Bytes vs runes
- []rune
- strings.Builder
héllo
h0
é1-2
l3
l4
o5
Bytes are not characters
A Go string is a sequence of bytes, and a character outside ASCII takes more than one byte. A rune is one Unicode character. Converting a string to []rune lets you work with characters instead of bytes.
héllo has 5 characters but 6 bytes, because é takes two bytes; that is why the positions printed by range jump from 1 to 3. []rune makes the characters editable. strings.Builder joins many pieces without creating a new string each time.
ประเด็นสำคัญ
- é takes two bytes in UTF-8.
- range gives runes, not bytes.
- []rune makes characters editable.
ตัวอย่าง Go ที่รันได้
main.go
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
word := "héllo"
fmt.Println(len(word), utf8.RuneCountInString(word))
parts := []string{}
for index, r := range word {
parts = append(parts, fmt.Sprintf("%d:%c", index, r))
}
fmt.Println(strings.Join(parts, " "))
runes := []rune(word)
runes[1] = 'e'
fmt.Println(string(runes), len(runes))
bytes := []byte("Go")
fmt.Println(bytes, string(bytes[0]))
var builder strings.Builder
for i := 3; i > 0; i-- {
fmt.Fprintf(&builder, "%d...", i)
}
builder.WriteString("go!")
fmt.Println(builder.String())
}
6 5
0:h 1:é 3:l 4:l 5:o
hello 5
[71 111] G
3...2...1...go!ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- Count Uppercase Letters Count the capital letters in a text. ง่าย
- ความถี่ของตัวอักษร นับจำนวนครั้งที่ตัวอักษรแต่ละตัวปรากฏขึ้น ง่าย