Skip to main content

If/else

If/else

If else is very similar to C except you just take out the parenthesis.

func main() {
	x := 10
	
	if x > 10 {
		fmt.Println("It is greater than 10")
	} else if x < 10 {
		fmt.Println("It is less than 10")
	} else {
		fmt.Println("It is equal to 10")
	}
}

Notice that theĀ else andĀ else if MUST be after the closing bracket of the previous statement. Otherwise, it will not compile.

Temporary variable

If/else generate it's own block, with this you can do something very interesting. You can declare and assign a variable that is only valid within that particular if/else block like such:

func main() {	
	if x := 10; x > 10 {
		fmt.Println("It is greater than 10")
	} else if x < 10 {
		fmt.Println("It is less than 10")
	} else {
		fmt.Println("It is equal to 10")
	}
}
Ternary operator?

No ternary operator, must use a full if/else branch for assignment of the variable.