Go cơ bản

Go Arrays

A fixed number of values of one type, and why assigning an array copies it.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • [5]int and [...]int
  • Arrays are values
  • Arrays of arrays
var scores [5]int
720
01
02
03
644
Items you do not set keep the zero value.

Fixed size, copied on assignment

An array holds a fixed number of values of one type, and its length is part of its type. Arrays are less common than slices in Go, but slices are built on top of them.

[5]int starts with five zeros. [...] lets the compiler count the items. Assigning an array copies every item, so changing copyOfPrimes leaves primes alone. An array of arrays makes a grid.

Những điểm quan trọng

  1. The length is part of the type.
  2. Assigning an array copies every item.
  3. Slices are built on arrays.

Ví dụ Go chạy được

Go
Chạy code →
main.go
package main

import "fmt"

func main() {
	var scores [5]int // fixed size, zero values
	scores[0] = 72
	scores[4] = 64
	fmt.Println(scores, len(scores))

	primes := [...]int{2, 3, 5, 7}
	copyOfPrimes := primes // arrays are values: this copies all items
	copyOfPrimes[0] = 99
	fmt.Println(primes, copyOfPrimes)

	grid := [2][3]int{{1, 2, 3}, {4, 5, 6}}
	fmt.Println(grid[1][2], grid)
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
[72 0 0 0 64] 5
[2 3 5 7] [99 3 5 7]
6 [[1 2 3] [4 5 6]]

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Slices →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách