If Else Statement

...

Go if else Statement

else bayonotidan shart noto'g'ri bo'lsa, bajarilishi kerak bo'lgan kod blokini aniqlash uchun foydalaniladi.

Sintaksis

if condition {
  // shart haqiqiy bo'lsa bajariladigan kod
} else {
  // shart noto'g'ri bo'lsa bajariladigan kod
}

if else Bayonotidan Foydalanish

Misol

Bu misolda, vaqt (20) 18 dan katta, shuning uchun if sharti noto'g'ri. Shuning uchun, else sharti bajariladi va ekranga "Good evening" (Yaxshi kech) matnini chiqaradi. Agar vaqt 18 dan kam bo'lsa, dastur "Good day" (Yaxshi kun) deb chiqarardi:

package main
import ("fmt")
 
func main() {
  time := 20
  if time < 18 {
    fmt.Println("Good day.")
  } else {
    fmt.Println("Good evening.")
  }
}

Misol

Bu misolda, harorat 14, shuning uchun if shart noto'g'ri va else bayonotidagi kod bajariladi:

package main
import ("fmt")
 
func main() {
  temperature := 14
  if temperature > 15 {
    fmt.Println("It is warm out there")
  } else {
    fmt.Println("It is cold out there")
  }
}

else bayonotidagi qavslar quyidagicha bo'lishi kerak: } else {

Misol

Agar else qavslarini boshqa qatorda qo'ysangiz, xato yuz beradi:

package main
import ("fmt")
 
func main() {
  temperature := 14
  if temperature > 15 {
    fmt.Println("It is warm out there.")
  } // bu xato beradi
  else {
    fmt.Println("It is cold out there.")
  }
}

Natija

./prog.go:9:3: syntax error: unexpected else, expecting }

Ushbu sahifada

Xato haqida xabar berish