Arrays in Go have a fixed size determined at declaration time. The array type includes both the length and element type. Arrays are value types in Go — when you assign an array to another variable, the entire array is copied. For this reason, arrays are rarely used directly; slices are used instead.
Mảng trong Go có kích thước cố định được xác định tại thời điểm khai báo. Kiểu mảng bao gồm cả chiều dài và kiểu phần tử. Các mảng là kiểu giá trị trong Go — khi bạn gán một mảng cho biến khác, toàn bộ mảng được sao chép. Do đó, các mảng ít khi được dùng trực tiếp; slice được sử dụng thay thế.
1package main23import "fmt"45func main() {6 // Array declaration with explicit length7 var arr [5]int8 fmt.Println(arr) // [0 0 0 0 0] (zero values)910 // Array with initializer11 numbers := [5]int{1, 2, 3, 4, 5}12 fmt.Println(numbers) // [1 2 3 4 5]Vì các mảng là kiểu giá trị, việc truyền mảng lớn làm cho copy lớn. Dùng slice hoặc con trỏ đến mảng để tránh điều này.
Slices are the primary way to work with sequences of elements in Go. A slice has length (len) and capacity (cap). Slices do not store data; they are a view into an underlying array. You create slices with s[low:high] syntax or the make() function. A nil slice is uninitialized; an empty slice has length 0 but can be grown.
Slice là cách chính để làm việc với chuỗi phần tử trong Go. Slice có độ dài (len) và dung lượng (cap). Slice không lưu trữ dữ liệu; nó là chế độ xem vào một mảng bên dưới. Bạn tạo slice bằng cú pháp s[low:high] hoặc hàm make(). Nil slice là slice chưa được gán; slice trống là slice có độ dài 0 nhưng có thể được mở rộng.
1package main23import "fmt"45func main() {6 // Slice from array7 arr := [6]int{1, 2, 3, 4, 5, 6}8 slice := arr[1:4]9 fmt.Println(slice) // [2 3 4]1011 // Slice syntax: s[low:high] (includes low, excludes high)12 fmt.Println(arr[:3]) // [1 2 3]Slice là tham chiếu đến mảng bên dưới. Nếu hai slice chia sẻ cùng một mảng bên dưới, thay đổi một slice sẽ ảnh hưởng đến mảng bên dưới mà cả hai nhìn thấy.
Maps in Go are unordered collections of key-value pairs. You create maps with make() or map literals. Go provides the comma-ok idiom to distinguish between 'key does not exist' and 'key has zero value'. Use delete() to remove entries from a map.
Map trong Go là một tập hợp cặp khóa-giá trị không có thứ tự. Bạn tạo map bằng make() hoặc map literal. Go cung cấp comma-ok idiom để phân biệt giữa 'khóa không tồn tại' và 'khóa có giá trị zero'. Dùng delete() để loại bỏ mục nhập khỏi map.
1package main23import "fmt"45func main() {6 // Creating a map with make7 scores := make(map[string]int)8 scores["Alice"] = 959 scores["Bob"] = 8710 scores["Carol"] = 921112 // Accessing valuesA struct is a collection of named fields grouped together. You define structs with the type keyword. Fields are initialized by name (map-like) or position. Go supports struct embedding for composition: a field without a name promotes the embedded struct's fields. This is not true inheritance — it is composition.
Struct là tập hợp các trường có tên được gom lại. Bạn định nghĩa struct với từ khóa type. Các trường được khởi tạo bằng tên (map-like) hoặc vị trí (position). Go hỗ trợ nhúng struct (struct embedding) cho thành phần: một trường không có tên hỗ trợ kế thừa giống như hành vi. Đây không phải là kế thừa thực sự — nó là thành phần.
1package main23import "fmt"45// Define a struct6type Person struct {7 Name string8 Age int9 City string10}1112// Struct with embedded struct for compositionStructs can have methods associated with them. A method is a function with a receiver. We will cover this in depth in the next chapter, but here is a quick preview.
Các struct có thể có các phương thức được liên kết với chúng. Một phương thức là một hàm có một người nhận (receiver). Chúng ta sẽ đi sâu hơn trong chương tiếp theo, nhưng đây là một cái nhìn thoáng qua.
1package main23import "fmt"45type Rectangle struct {6 Width float647 Height float648}910// Method with value receiver11func (r Rectangle) Area() float64 {12 return r.Width * r.HeightWhen you assign a struct to another variable, the entire struct is copied (value semantics). If you want to share a struct and have changes visible elsewhere, use a pointer (pointer semantics). In Go, this is explicit — you will see &struct or *Struct in the code.
Khi bạn gán struct cho biến khác, toàn bộ struct được sao chép (value semantics). Nếu bạn muốn chia sẻ struct và cho phép các thay đổi được nhìn thấy ở các nơi khác, dùng con trỏ (pointer semantics). Trong Go, điều này là rõ ràng — bạn sẽ thấy &struct hoặc *Struct trong code.
1package main23import "fmt"45type Account struct {6 Balance float647}89// Value receiver: method gets a copy of the struct10func (a Account) Deposit(amount float64) {11 a.Balance += amount12}Key Takeaways
Điểm Chính
- Arrays have fixed size; slices are dynamic views into arraysMảng có kích thước cố định; slice là chế độ xem động vào mảng
- Maps are unordered key-value collections; use comma-ok to check key existenceMap là bộ sưu tập cặp khóa-giá trị không có thứ tự; dùng comma-ok để kiểm tra tồn tại khóa
- Structs group related fields; embedding enables composition over inheritanceStruct nhóm các trường liên quan; nhúng cho phép thành phần thay vì kế thừa
- Pointer receivers modify structs in place; value receivers work on copiesCon trỏ receiver sửa đổi struct tại chỗ; receiver giá trị hoạt động trên bản sao
Practice
Test your understanding of this chapter
What is the key difference between an array and a slice in Go?
Sự khác biệt chính giữa mảng và slice trong Go là gì?
What does the comma-ok idiom accomplish in map access?
Thành ngữ comma-ok đạt được gì trong truy cập map?
In Go, when you assign one struct to another variable, the entire struct is copied, making them independent values.
Trong Go, khi bạn gán một struct cho biến khác, toàn bộ struct được sao chép, làm cho chúng trở thành các giá trị độc lập.
Slices always contain their own data; they are independent copies of underlying arrays.
Slice luôn chứa dữ liệu của riêng chúng; chúng là những bản sao độc lập của mảng bên dưới.
Complete the struct embedding pattern
Hoàn thành mô hình nhúng struct
type Address struct { Street string City string } type Person struct { // Embed Address to promote Street and City Name string }