พื้นฐาน Go

Go for Loops

Go has one loop keyword. See its four forms: counting, while-style, infinite and range.

  • ระดับเริ่มต้น
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • The three-part for
  • for as a while loop
  • range
for i := 1; i <= 3; i++
1print
2print
3print
4stop
The loop ends when i <= 3 is false.

One keyword, four forms

Go has one loop keyword: for. It can count with three parts, repeat while a condition is true, run forever until break, or visit every item with range.

The first loop has a start, a condition and a step. The second has only a condition, like while in other languages. The third has nothing and ends with break. range over a string gives the position and the character of each letter.

ประเด็นสำคัญ

  1. for i := 1; i <= 3; i++ counts.
  2. for condition { } works like while.
  3. range visits every item.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		fmt.Println("for:", i)
	}

	countdown := 3
	for countdown > 0 { // a while loop
		fmt.Println("while:", countdown)
		countdown--
	}

	total := 0
	for { // an infinite loop, left with break
		total += 10
		if total >= 30 {
			break
		}
	}
	fmt.Println("loop result:", total)

	for index, letter := range "Go" {
		fmt.Println(index, string(letter))
	}
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
for: 1
for: 2
for: 3
while: 3
while: 2
while: 1
loop result: 30
0 G
1 o

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Prime Numbers →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด