Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Bootcamps Get Certified Upgrade Teachers Spaces Bootcamps
   ❮   
     ❯   

Go else if Statement


The else if Statement

Use theelse if statement to specify a new condition if the first condition isfalse.

Syntax

ifcondition1 {
   // code to be executed if condition1 is true
} else ifcondition2 {
   // code to be executed if condition1 is false and condition2 is true
} else {
   // code to be executed if condition1 and condition2 are both false
}

Using The else if Statement

Example

This example shows how to use anelse if statement.

package main
import ("fmt")

func main() {
  time := 22
  if time < 10 {
    fmt.Println("Good morning.")
  } else if time < 20 {
    fmt.Println("Good day.")
  } else {
    fmt.Println("Good evening.")
  }
}

Result:

Good evening.
Try it Yourself »

Example explained

In the example above, time (22) is greater than 10, so thefirst condition isfalse. The next condition, in theelse if statement, is alsofalse, so we move on toelse condition sincecondition1 andcondition2 are bothfalse - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Example

Another example for the use ofelse if.

package main
import ("fmt")

func main() {
  a := 14
  b := 14
  if a < b {
    fmt.Println("a is less than b.")
  } else if a > b {
    fmt.Println("a is more than b.")
  } else {
    fmt.Println("a and b are equal.")
  }
}

Result:

a and b are equal.
Try it Yourself »

Example

Note: If condition1 and condition2 are BOTH true, only the code for condition1 are executed:

package main
import ("fmt")

func main() {
  x := 30
  if x >= 10 {
    fmt.Println("x is larger than or equal to 10.")
  } else if x > 20 {
    fmt.Println("x is larger than 20.")
  } else {
    fmt.Println("x is less than 10.")
  }
}

Result:

x is larger than or equal to 10.
Try it Yourself »



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2026 Movatter.jp