พื้นฐาน Go
Go Arrays
A fixed number of values of one type, and why assigning an array copies it.
สิ่งที่คุณจะได้เรียนรู้
- [5]int and [...]int
- Arrays are values
- Arrays of arrays
var scores [5]int
720
01
02
03
644
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.
ประเด็นสำคัญ
- The length is part of the type.
- Assigning an array copies every item.
- Slices are built on arrays.
ตัวอย่าง Go ที่รันได้
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)
}
[72 0 0 0 64] 5
[2 3 5 7] [99 3 5 7]
6 [[1 2 3] [4 5 6]]ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- หาค่าสูงสุดในอาเรย์ หาค่าที่มากที่สุดในลิสต์ ง่าย
- Min and Max Together Find the smallest and largest value in one pass. ง่าย