Go’da Dilim Üzerinde Dön ve Eşleşmeleri Say
Senaryo
countOpenRooms fonksiyonunun Go sürümünü özdeş ortak kural testleriyle incele.
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.
| Seçenek | Sonuç |
|---|---|
| countOpenRooms([]int{}) | Sonucu görmek için yukarıdan bir seçenek tıkla. |
| countOpenRooms([]int{1}) | Sonucu görmek için yukarıdan bir seçenek tıkla. |
| for _, seats := range seatCounts ve for seats := range seatCounts | Sonucu görmek için yukarıdan bir seçenek tıkla. |
Açıklamayı göster
- countOpenRooms([]int{})
0 — Python ve JavaScript ile birebir aynı.
- countOpenRooms([]int{1})
1 — Python ve JavaScript ile birebir aynı.
- 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
Tarayıcı ilerlemeni kaydedemedi. Değişiklikler bu sayfadan ayrılana kadar geçerli.