พื้นฐาน Go
Go Slices: append, len and cap
The list type you will use most in Go: grow it with append, cut it with [a:b], and watch out for shared memory.
สิ่งที่คุณจะได้เรียนรู้
- append
- Slicing with [a:b]
- make, len and cap
numbers[1:4]
30
11
42
13
54
A growable view of an array
A slice is a view of an array that can grow. It is the list type you will use most in Go. append adds items and returns the updated slice.
numbers[1:4] takes the items at positions 1, 2 and 3. That new slice shares memory with numbers, so changing middle[0] also changes numbers[1]. make creates an empty slice with room for three items, and cap shows that room.
ประเด็นสำคัญ
- append returns the updated slice.
numbers[1:4]has the items at 1, 2 and 3.- A slice shares memory with the slice it was cut from.
ตัวอย่าง Go ที่รันได้
main.go
package main
import "fmt"
func main() {
numbers := []int{3, 1, 4}
numbers = append(numbers, 1, 5)
fmt.Println(numbers, len(numbers))
middle := numbers[1:4]
fmt.Println(middle)
middle[0] = 100 // a slice shares the array it was cut from
fmt.Println(numbers)
squares := make([]int, 0, 3)
for i := 1; i <= 3; i++ {
squares = append(squares, i*i)
}
fmt.Println(squares, len(squares), cap(squares))
for index, value := range squares {
fmt.Println(index, value)
}
}
[3 1 4 1 5] 5
[1 4 1]
[3 100 4 1 5]
[1 4 9] 3 3
0 1
1 4
2 9ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- หาผลรวมของอาเรย์ หาผลรวมของค่าทั้งหมดในลิสต์ ง่าย
- หมุนอาเรย์ หมุนลิสต์ไปทางขวาตามจำนวนขั้นที่กำหนด ง่าย