Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Conditional Statements | Control Structures
Introduction to GoLang
course content

Зміст курсу

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

Conditional Statements

Conditional Statements, also known as if-else statements, are used to execute a block of code based on a condition.

Conditions are represented by boolean expressions, which we briefly explored in the second section's "Booleans" chapter. To recall, a boolean expression is a combination of logical and/or comparison operations and may or may not include other operators.

A conditional statement uses if, else if, and else keywords. The syntax for writing a simple conditional statement is as follows:

If the value of the 'expression' in the parentheses is true, the code enclosed in the curly brackets is executed. Otherwise, it is ignored. Here is an example:

go

index

copy
12345678910
package main import "fmt" func main() { fmt.Println("Before if-condition") if (3 < 4) { fmt.Println("3 is greater than 4") } fmt.Println("After if-condition") }

Since the expression 3 < 4 evaluates to true, the code inside the curly braces is executed. If we modify the expression to make it false, the Println statement won't be executed.

go

index

copy
12345678910
package main import "fmt" func main() { fmt.Println("Before if-condition") if (3 > 4) { fmt.Println("3 is greater than 4") } fmt.Println("After if-condition") }

The following diagram shows the execution of the if-condition:

You can use the else keyword to specify code that should be executed when the condition is not met. The else statement does not require a boolean expression.

go

index

copy
1234567891011
package main import "fmt" func main() { var value int = 70 if (value <= 50) { fmt.Println("The value is less or equal to 50") } else { fmt.Println("The value is greater than 50") } }

Here's how the execution flow unfolds when we use else in the condition:

Which keyword is used for writing an if statement in Go?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 3. Розділ 2
We're sorry to hear that something went wrong. What happened?
some-alt