Skip to content
Skip to content
DocsGo LearningintermediateData Structures
Chapter 5 of 14·intermediate·8 min read

Data Structures

Cấu Trúc Dữ Liệu

Arrays, slices, maps, and structs

Hover or tap any paragraph to see Vietnamese translation

Arrays

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.

arrays.go
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]
Warning
Because arrays are value types, passing large arrays creates expensive copies. Use slices or pointers to arrays to avoid this.

Slices — Dynamic Arrays

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.

slices.go
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]
Info
Slices are references to an underlying array. If two slices share the same underlying array, modifying one slice affects the underlying array that both see.

Maps

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.

maps.go
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 values

Structs

A 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.

structs.go
1package main23import "fmt"45// Define a struct6type Person struct {7    Name string8    Age  int9    City string10}1112// Struct with embedded struct for composition

Struct Methods Preview

Structs 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.

struct_methods_preview.go
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.Height

Pointer vs Value Semantics

When 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.

pointer_semantics.go
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

Quiz

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ì?

Quiz

What does the comma-ok idiom accomplish in map access?

Thành ngữ comma-ok đạt được gì trong truy cập map?

True or False

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.

True or False

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.

Code Challenge

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
}
Built: 6/25/2026, 3:03:36 PM