Ders programı

Ders programı

Go’da Dilim Üzerinde Dön ve Eşleşmeleri Say

Senaryo

countOpenRooms fonksiyonunun Go sürümünü özdeş ortak kural testleriyle incele.

Seçilen durumAşağıdan bir seçenek seç
Sonuç—
Go
func countOpenRooms(seatCounts []int) int {
	openRooms := 0
	for _, seats := range seatCounts {
		if seats > 0 {
			openRooms++
		}
	}
	return openRooms
}

Sıra sende

Her Go durumunu karşılaştır ve alt çizgi _ kullanımının neden kritik olduğunu gör.

Açıklamayı göster
  1. countOpenRooms([]int{})

    0 — Python ve JavaScript ile birebir aynı.

  2. countOpenRooms([]int{1})

    1 — Python ve JavaScript ile birebir aynı.

  3. for _, seats := range seatCounts ve for seats := range seatCounts

    Go range’de tek değişken DEĞERİ değil DİZİNİ (0, 1, 2) alır! Değer için hep _, seats yaz.

Go’da en yaygın başlangıç hatası "for seats := range seatCounts" yazıp değer yerine dizinleri kontrol etmektir.

Önce gözden geçir
Ortak test durumlarını indir

Sıra sende

Go’da countPassing(scores []int) int yaz ve alt çizgiyi _ atlarsan ne olacağını açıkla.

Sık yapılan hata "for score := range scores" yazarak puan yerine dizini >= 60 ile kıyaslamak.

Çalışmanı kontrol et

for _, score := range scores { if score >= 60 { passed++ } }.

Kısa kontrol

Go’da "for x := range []int{50, 90}" döngüsü x’e ne atar?
Yanıtı ve gerekçesini göster

Doğru yanıt 0 ve 1 dizinlerini (50 ve 90’ı değil)

Go’da tek değişkenli range her zaman dizini verir; değer için _, x gerekir.