If else statement

Welcome to tutorial number 8 of our Golang tutorial series .

if statement has a condition and it executes a block of code if that condition evaluates to true . It executes an alternate else block if the condition evaluates to false . In this tutorial we will look at the various syntaxes for using a if statement.

If statement syntax

The syntax of the if statement is provided below

If the condition evaluates to true , the block of code between the braces { and } is executed.

Unlike in other languages like C, the braces { } are not optional and they are mandatory even if there is only one line of code between the braces { } .

Let’s write a simple program to find out whether a number is even or odd.

Run in Playground

In the above program, the condition num%2 in line no. 9 finds whether the remainder of dividing num by 2 is zero or not. Since it is 0 in this case, the text The number 10 is even is printed and the program exits.

The if statement has an optional else construct which will be executed if the condition in the if statement evaluates to false .

In the above snippet, if condition evaluates to false , then the block of code between else { and } will be executed.

Let’s rewrite the program to find whether the number is odd or even using if else statement.

Run in playground

In the above code, instead of returning if the condition is true as we did in the previous section , we create an else statement that will be executed if the condition is false . In this case, since 11 is odd, the if condition is false and the lines of code within the else statement is executed. The above program will print.

If … else if … else statement

The if statement also has optional else if and else components. The syntax for the same is provided below

The condition is evaluated for the truth from the top to bottom.

In the above statement, if condition1 is true, then the block of code within if condition1 { and the closing brace } is executed.

If condition1 is false and condition2 is true, then the block of code within else if condition2 { and the next closing brace } is executed.

If both condition1 and condition2 are false, then the block of code in the else statement between else { and } is executed.

There can be any number of else if statements.

In general, whichever if or else if ’s condition evaluates to true , it’s corresponding code block is executed. If none of the conditions are true then else block is executed.

Let’s write a bus ticket pricing program using else if . The program must satisfy the following requirements.

  • If the age of the passenger is less than 5 years, the ticket is free.
  • If the age of the passenger is between 5 and 22 years, then the ticket is $10.
  • If the age of the passenger is above 22 years, then the ticket price is $15.

In the above program, the age of the passenger is set to 10 . The condition in line no. 12 is true and hence the program will print

Please try changing the age to test whether the different blocks of the if else statement are executed as expected.

If with assignment

There is one more variant of if which includes an optional shorthand assignment statement that is executed before the condition is evaluated. Its syntax is

In the above snippet, assignment-statement is first executed before the condition is evaluated.

Let’s rewrite the program which calculates the bus ticket price using the shorthand syntax.

In the above program age is initialized in the if statement in line no. 9. age can be accessed from only within the if construct. i.e. the scope of age is limited to the if , else if and else blocks. If we try to access age outside the if , else if or else blocks, the compiler will complain. This syntax often comes in handy when we declare a variable just for the purpose of if else construct. Using this syntax in such cases ensures that the scope of the variable is only within the if statement.

The else statement should start in the same line after the closing curly brace } of the if statement. If not the compiler will complain.

Let’s understand this by means of a program.

In the program above, the else statement does not start in the same line after the closing } of the if statement in line no. 11 . Instead, it starts in the next line. This is not allowed in Go. If you run this program, the compiler will print the error,

The reason is because of the way Go inserts semicolons automatically. You can read about the semicolon insertion rule here https://go.dev/ref/spec#Semicolons .

In the rules, it’s specified that a semicolon will be inserted after closing brace } , if that is the final token of the line. So a semicolon is automatically inserted after the if statement’s closing braces } in line no. 11 by the Go compiler.

So our program actually becomes

after semicolon insertion. The compiler would have inserted a semicolon in line no. 4 of the above snippet.

Since if{...} else {...} is one single statement, a semicolon should not be present in the middle of it. Hence this program fails to compile. Therefore it is a syntactical requirement to place the else in the same line after the if statement’s closing brace } .

I have rewritten the program by moving the else after the closing } of the if statement to prevent the automatic semicolon insertion.

Now the compiler will be happy and so are we 😃.

Idiomatic Go

We have seen various if-else constructs and we have in fact seen multiple ways to write the same program. For example, we have seen multiple ways to write a program that checks whether the number is even or odd using different if else constructs. Which one is the idiomatic way of coding in Go? In Go’s philosophy, it is better to avoid unnecessary branches and indentation of code. It is also considered better to return as early as possible. I have provided the program from the previous section below,

The idiomatic way of writing the above program in Go’s philosophy is to avoid the else and return from the if if the condition is true .

In the above program, as soon as we find out the number is even, we return immediately. This avoids the unnecessary else code branch. This is the way things are done in Go 😃. Please keep this in mind whenever writing Go programs.

I hope you liked this tutorial. Please leave your feedback and comments. Please consider sharing this tutorial on twitter or LinkedIn . Have a good day.

Next tutorial - Loops

if assignment golang

Go if..else, if..else..if, nested if with Best Practices

September 7, 2022

Introduction

In computer programming, conditional statements help you make decisions based on a given condition. The conditional statement evaluates if a condition is true or false, therefore it is worth noting that if statements work with boolean values. Just like other programming languages, Go has its own construct for conditional statements. In this tutorial , we will learn about different types of conditional statements in Go.

Below are the topics that we will cover

  • If statement
  • If - Else statement
  • If -else if else statement
  • Nested If statement
  • Logical operators AND , OR and NOT
  • Using multiple conditions if if else

Supported Comparison Operators in GO

Before we go ahead learning about golang if else statement, let us be familiar with supported comparison operators as you may need to use them in the if else conditions for decision making:

Operator Description Example
== Equal to num == 0
!= Not equal to num != 0
< Less than num < 0
<= Less than or equal to num <= 0
> Greater than num > 0
>= Greater than or equal to num >= 0

if statement

If a statement is used to specify  a block of code that should be executed if  a certain condition is true .

Explanation

In the above syntax, the keyword if is used to declare the beginning of an if statement, followed by a condition that is being tested. The condition should be a value of boolean type , the the block of code between opening and closing curly brackets will be executed only if the condition is true . In the next example, we define code that will only run if age is above 18 years.

In the preceding example, we define the age and ageLimit variables. In the if statement we compare the value of age and ageLimit by checking which is greater. The statement age > ageLimit will evaluate to true because 19 is greater than 18. The code block will be executed because the condition is true .

One liner if statement

We can also convert our if condition to run in one line, for example here I have written the same if condition in 2 different ways, one is multi line while the other is using single line:

if else Statement

If Else statement is used to evaluate both conditions that might be true or false. In the previous example, we did not really care if a condition evaluates to false. We use If Else conditional statements to handle both true and false outcomes.

In the preceding example, we define the age and ageLimit variables. In the if statement we compare the value of age and ageLimit by checking which is greater. The statement age > ageLimit will evaluate to false because 12 is less than 18. The second code block will be executed because the condition is false .

if else if statement

If Else If statement is used to specify a new condition if the first condition is false. When using If Else If statement, you can nest as many If Else conditions as you desire.

In the above example, the first if statement evaluates to false because age (17) is not greater than ageLimit(18) . We then check again if age is equal to 17, which evaluates to true . The block of code inside this section will be executed.

Nested if Statement

Nested if Statement, is a If conditional statement that has an If statement inside another If statement. The nested If statement will always be executed only if the outer If statement evaluates to true.

In the above syntax, the second if statement with condition labeled conditionY is housed inside the outer If statement with condition labeled conditionX . As long as condition labeled conditionX is true , if conditionY will be executed.

Supported Logical Operators in GO

We also have some logical operators on golang which help us when we have to check for multiple conditions:

if else statements using logical operator

In Go we use logical operators together with If conditional statements to achieve certain goals in our code. Logical operators return/execute to boolean values, hence making more sense using them conditional statements. Below are definitions of the three logical operators in Go.

Using logical AND operator

Checks of both operands are none zero. In case both operands are none-zero, a true value will be returned, else a false value will be returned. The operator representing logical AND is && .

Using logical OR operator

Check if one operand is true. In case one operand is true code will be executed. The operator representing logical OR is || .

Using logical NOT operator

Reverses the logical state of its operands. If a condition is  true, the logical operator NOT will change it to false. The operator representing logical Not is ! .

Using multiple condition in golang if else statements

We can also add multiple conditional blocks inside the if else statements to further enhance the decision making. Let us check some more examples covering if else multiple condition:

if statement with 2 logical OR Operator

Here we are checking if our num is more than 100 or less than 900:

if statement with 3 logical OR Operator

In this example we add one more OR condition to the if condition:

Using both logical AND and OR operator in single if statement

We can also use both AND and OR operator inside a single if statement, here is an example:

Using multiple conditions with if..else..if..else statement

Now we have used multiple conditions in our if condition but you can use the same inside else..if condition or combine it with if..else..if statements.

In Go, we use conditional statements  to handle decisions precisely in code. They enable our code to perform different computations or actions depending on whether a condition is true or false . In this article we have learned about different if conditional statements like If, If Else, If Else If Else, Nested If statements

https://go.dev/tour/flowcontrol https://www.golangprograms.com/golang-if-else-statements.html

Related Keywords: golang if else shorthand, golang if else one line, golang if else multiple conditions, golang if else string, golang if true, golang if else best practices, golang if statement with assignment, golang if not

Antony Shikubu

Antony Shikubu

He is highly skilled software developer with expertise in Python, Golang, and AWS cloud services. Skilled in building scalable solutions, he specializes in Django, Flask, Pandas, and NumPy for web apps and data processing, ensuring robust and maintainable code for diverse projects. You can reach out to him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

Save my name and email in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

if assignment golang

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Recent Comments

Popular posts, 7 tools to detect memory leaks with examples, 100+ linux commands cheat sheet & examples, tutorial: beginners guide on linux memory management, top 15 tools to monitor disk io performance with examples, overview on different disk types and disk interface types, 6 ssh authentication methods to secure connection (sshd_config), how to check security updates list & perform linux patch management rhel 6/7/8, 8 ways to prevent brute force ssh attacks in linux (centos/rhel 7).

Privacy Policy

HTML Sitemap

  • DigitalOcean
  • Sign up for:

How To Write Conditional Statements in Go

  • Development

author

Gopher Guides

How To Write Conditional Statements in Go

Introduction

Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.

When we fully execute each statement of a program, we are not asking the program to evaluate specific conditions. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.

Let’s look at some examples where we would use conditional statements:

  • If the student receives over 65% on her test, report that her grade passes; if not, report that her grade fails.
  • If he has money in his account, calculate interest; if he doesn’t, charge a penalty fee.
  • If they buy 10 oranges or more, calculate a discount of 5%; if they buy fewer, then don’t.

Through evaluating conditions and assigning code to run based on whether or not those conditions are met, we are writing conditional code.

This tutorial will take you through writing conditional statements in the Go programming language.

If Statements

We will start with the if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

In a plain text editor, open a file and write the following code:

With this code, we have the variable grade and are giving it the integer value of 70 . We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65 . If it does meet this condition, we are telling the program to print out the string Passing grade .

Save the program as grade.go and run it in a local programming environment from a terminal window with the command go run grade.go .

In this case, the grade of 70 does meet the condition of being greater than or equal to 65, so you will receive the following output once you run the program:

Let’s now change the result of this program by changing the value of the grade variable to 60 :

When we save and run this code, we will receive no output because the condition was not met and we did not tell the program to execute another statement.

To give one more example, let us calculate whether a bank account balance is below 0. Let’s create a file called account.go and write the following program:

When we run the program with go run account.go , we’ll receive the following output:

In the program we initialized the variable balance with the value of -5 , which is less than 0. Since the balance met the condition of the if statement ( balance < 0 ), once we save and run the code, we will receive the string output. Again, if we change the balance to 0 or a positive number, we will receive no output.

Else Statements

It is likely that we will want the program to do something even when an if statement evaluates to false. In our grade example, we will want output whether the grade is passing or failing.

To do this, we will add an else statement to the grade condition above that is constructed like this:

Since the grade variable has the value of 60 , the if statement evaluates as false, so the program will not print out Passing grade . The else statement that follows tells the program to do something anyway.

When we save and run the program, we’ll receive the following output:

If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade .

To add an else statement to the bank account example, we rewrite the code like this:

Here, we changed the balance variable value to a positive number so that the else statement will print. To get the first if statement to print, we can rewrite the value to a negative number.

By combining an if statement with an else statement, you are constructing a two-part conditional statement that will tell the computer to execute certain code whether or not the if condition is met.

Else if Statements

So far, we have presented a Boolean option for conditional statements, with each if statement evaluating to either true or false. In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Go as else if . The else if or else if statement looks like the if statement and will evaluate another condition.

In the bank account program, we may want to have three discrete outputs for three different situations:

  • The balance is below 0
  • The balance is equal to 0
  • The balance is above 0

The else if statement will be placed between the if statement and the else statement as follows:

Now, there are three possible outputs that can occur once we run the program:

  • If the variable balance is equal to 0 we will receive the output from the else if statement ( Balance is equal to 0, add funds soon. )
  • If the variable balance is set to a positive number, we will receive the output from the else statement ( Your balance is 0 or above. ).
  • If the variable balance is set to a negative number, the output will be the string from the if statement ( Balance is below 0, add funds now or you will be charged a penalty ).

What if we want to have more than three possibilities, though? We can do this by writing more than one else if statement into our code.

In the grade.go program, let’s rewrite the code so that there are a few letter grades corresponding to ranges of numerical grades:

  • 90 or above is equivalent to an A grade
  • 80-89 is equivalent to a B grade
  • 70-79 is equivalent to a C grade
  • 65-69 is equivalent to a D grade
  • 64 or below is equivalent to an F grade

To run this code, we will need one if statement, three else if statements, and an else statement that will handle all failing cases.

Let’s rewrite the code from the preceding example to have strings that print out each of the letter grades. We can keep our else statement the same.

Since else if statements will evaluate in order, we can keep our statements pretty basic. This program is completing the following steps:

If the grade is greater than 90, the program will print A grade , if the grade is less than 90, the program will continue to the next statement…

If the grade is greater than or equal to 80, the program will print B grade , if the grade is 79 or less, the program will continue to the next statement…

If the grade is greater than or equal to 70, the program will print C grade , if the grade is 69 or less, the program will continue to the next statement…

If the grade is greater than or equal to 65, the program will print D grade , if the grade is 64 or less, the program will continue to the next statement…

The program will print Failing grade because all of the above conditions were not met.

Nested If Statements

Once you are feeling comfortable with the if , else if , and else statements, you can move on to nested conditional statements. We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested if statement:

A few possible outputs can result from this code:

  • If statement1 evaluates to true, the program will then evaluate whether the nested_statement also evaluates to true. If both cases are true, the output will be:
Output true yes
  • If, however, statement1 evaluates to true, but nested_statement evaluates to false, then the output will be:
Output true no
  • And if statement1 evaluates to false, the nested if-else statement will not run, so the else statement will run alone, and the output will be:
Output false

We can also have multiple if statements nested throughout our code:

In this code, there is a nested if statement inside each if statement in addition to the else if statement. This will allow for more options within each condition.

Let’s look at an example of nested if statements with our grade.go program. We can check for whether a grade is passing first (greater than or equal to 65%), then evaluate which letter grade the numerical grade should be equivalent to. If the grade is not passing, though, we do not need to run through the letter grades, and instead can have the program report that the grade is failing. Our modified code with the nested if statement will look like this:

If we run the code with the variable grade set to the integer value 92 , the first condition is met, and the program will print out Passing grade of: . Next, it will check to see if the grade is greater than or equal to 90, and since this condition is also met, it will print out A .

If we run the code with the grade variable set to 60 , then the first condition is not met, so the program will skip the nested if statements and move down to the else statement, with the program printing out Failing grade .

We can of course add even more options to this, and use a second layer of nested if statements. Perhaps we will want to evaluate for grades of A+, A and A- separately. We can do so by first checking if the grade is passing, then checking to see if the grade is 90 or above, then checking to see if the grade is over 96 for an A+:

In this code, for a grade variable set to 96 , the program will run the following:

  • Check if the grade is greater than or equal to 65 (true)
  • Print out Passing grade of:
  • Check if the grade is greater than or equal to 90 (true)
  • Check if the grade is greater than 96 (false)
  • Check if the grade is greater than 93 and also less than or equal to 96 (true)
  • Leave these nested conditional statements and continue with remaining code

The output of the program for a grade of 96 therefore looks like this:

Nested if statements can provide the opportunity to add several specific levels of conditions to your code.

By using conditional statements like the if statement, you will have greater control over what your program executes. Conditional statements tell the program to evaluate whether a certain condition is being met. If the condition is met it will execute specific code, but if it is not met the program will continue to move down to other code.

To continue practicing conditional statements, try using different operators to gain more familiarity with conditional statements.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

Tutorial Series: How To Code in Go

Go (or GoLang) is a modern programming language originally developed by Google that uses high-level syntax similar to scripting languages. It is popular for its minimal syntax and innovative handling of concurrency, as well as for the tools it provides for building native binaries on foreign platforms.

  • 1/53 How To Code in Go eBook
  • 2/53 How To Install Go and Set Up a Local Programming Environment on Ubuntu 18.04
  • 3/53 How To Install Go and Set Up a Local Programming Environment on macOS

Default avatar

Still looking for an answer?

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

There is currently no mention of “switch/case” in this tutorial. I think it would be a good to add a few examples, since the page is about conditionals in general, not just “if/then/else”. For example: https://gobyexample.com/switch

I suggest mentioning the ternary operator in Go, or rather, the lack of one. Some readers (like me) might waste time looking for a “? :” ternary switch in the Go documentation, only to eventually discover that the language designers decided against it.

Arguably, a long list of conditionals is sometimes best expressed as a data structure. For example, create a structure which somehow associates the number 1 with the string “one”, and then create a function which takes in a number and prints the associated string. I’m not sure if such an example would be a worthwhile addition to a basic tutorial on conditionals, but personally I’d include it.

Creative Commons

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Popular Topics

  • Linux Basics
  • All tutorials
  • Talk to an expert

Join the Tech Talk

Please complete your information!

Featured on Community

if assignment golang

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

if assignment golang

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

if assignment golang

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Featured Tutorials

Digitalocean products, welcome to the developer cloud.

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Popular Articles

  • Using Select Statement With Channels (Jun 24, 2024)
  • Using Channels For Communication (Jun 24, 2024)
  • Introduction To Channels (Jun 24, 2024)
  • Working With Goroutines (Jun 24, 2024)
  • Introduction To Goroutines (Jun 24, 2024)

Golang If Statement

Switch to English

Table of Contents

Understanding the GoLang If Statement

Using the if statement correctly, golang if-else statement, golang if-elseif-else statement, common errors and how to avoid them.

Introduction As an online educator for GoLang, a statically typed, compiled language that was created at Google, I'm here to simplify the concept of the If statement. The if statement is a fundamental part of GoLang that allows your programs to make decisions based on certain conditions. It's a powerful feature that can greatly increase the versatility of your programs and scripts.

  • The if statement in GoLang is used for decision making. It allows your program to execute a particular section of code if a specific condition is true. If the condition is false, the program will skip that section of code and move on to the next part.
  • When using the if statement, you should always ensure that your condition is valid and that it will return either true or false. If your condition does not return a boolean value, you will get a compilation error.
  • In addition to the if statement, GoLang also has an if-else statement. This allows you to specify an alternate section of code to be executed if the condition in the if statement is false.
  • For more complex decision making, GoLang provides the if-elseif-else statement. This allows you to specify multiple conditions and execute different sections of code based on which condition is true.
  • One common error is forgetting to use braces {} to enclose the code block that should be executed if the condition is true. Unlike some other programming languages, GoLang requires these braces even if there's only one line of code in the block.
  • Another common error is incorrect use of the equality operator (==). Remember that in GoLang, as in most programming languages, a single equals sign (=) is used for assignment, while a double equals sign (==) is used for comparison.
  • Also, keep in mind that GoLang is case sensitive. This means that the variables 'a' and 'A' are considered to be different. So, always ensure that you're using the correct case when referencing variables in your conditions.

Go by Example : If/Else

Branching with and in Go is straight-forward.

main
"fmt"
main() {

Here’s a basic example.

7%2 == 0 { fmt.Println("7 is even") } else { fmt.Println("7 is odd") }

You can have an statement without an else.

8%4 == 0 { fmt.Println("8 is divisible by 4") }

Logical operators like and are often useful in conditions.

8%2 == 0 || 7%2 == 0 { fmt.Println("either 8 or 7 are even") }

A statement can precede conditionals; any variables declared in this statement are available in the current and all subsequent branches.

num := 9; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { fmt.Println(num, "has 1 digit") } else { fmt.Println(num, "has multiple digits") } }

Note that you don’t need parentheses around conditions in Go, but that the braces are required.

go run if-else.go 7 is odd 8 is divisible by 4 either 8 or 7 are even 9 has 1 digit

There is no in Go, so you’ll need to use a full statement even for basic conditions.

Next example: Switch .

by Mark McGranaghan and Eli Bendersky | source | license

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, go introduction.

  • Golang Getting Started
  • Go Variables
  • Go Data Types
  • Go Print Statement
  • Go Take Input
  • Go Comments
  • Go Operators
  • Go Type Casting

Go Flow Control

  • Go Boolean Expression
  • Go if...else
  • Go for Loop

Go while Loop

Go break and continue

Go Data Structures

  • Go Functions
  • Go Variable Scope
  • Go Recursion
  • Go Anonymous Function
  • Go Packages

Go Pointers & Interface

  • Go Pointers
  • Go Pointers and Functions
  • Go Pointers to Struct
  • Go Interface
  • Go Empty Interface
  • Go Type Assertions

Go Additional Topics

  • Go defer, panic, and recover

Go Tutorials

Go Booleans (Relational and Logical Operators)

In computer programming, we use the if statement to run a block code only when a certain condition is met.

For example, assigning grades (A, B, C) based on marks obtained by a student.

  • if the percentage is above 90 , assign grade A
  • if the percentage is above 75 , assign grade B
  • if the percentage is above 65 , assign grade C
  • Go if statement

The syntax of the if statement in Go programming is:

If test_condition evaluates to

  • true - statements inside the body of if are executed.
  • false - statements inside the body of if are not executed.

Working of if statement in Go programming

Example: Simple if statement in Golang

In the above example, we have created a variable named number . Notice the test_condition ,

Here, since the variable number is greater than 0 , the test_condition evaluates true .

If we change the variable to a negative integer. Let's say -5 .

Now, when we run the program, the output will be:

This is because the value of number is less than 0 . Hence, the test_condition evaluates to false . And, the body of the if block is skipped.

  • Go if...else statement

The if statement may have an optional else block. The syntax of the if..else statement is:

If test_condition evaluates to true ,

  • the code inside if is executed
  • the code inside else is skipped

If test_condition evaluates to false ,

  • the code inside else is executed
  • the code inside if is skipped

Working of if...else in Go programming

Example: if...else statement in Golang

The number is 10 , so the test condition number > 0 is evaluated to be true . Hence, the statement inside the body of if is executed.

Now if we run the program, the output will be:

Here, the test condition evaluates to false . Hence code inside the body of else is executed.

Note : The else statement must start in the same line where the if statement ends.

  • Go if...else if ladder

The if...else statement is used to execute a block of code among two alternatives.

However, if you need to make a choice between more than two alternatives, then we use the else if statement.

if test_condition1 evaluates to true

  • code block 1 is executed
  • code block 2 and code block 3 are skipped

if test_condition2 evaluates to true

  • code block 2 is executed
  • code block 1 and code block 3 are skipped

if both test conditions evaluates to false

  • code block 3 is executed
  • code block 1 and code block 2 are skipped

Working of if.. else if..else in Go programming.

Example: if...if else ladder statement in Golang

Here, both the test conditions number1 == number2 and number1 > number2 are false . Hence the code inside the else block is executed.

  • Go nested if statement

You can also use an if statement inside of an if statement. This is known as a nested if statement.

Example: Nested if statement in Golang

If the outer condition number1 >= number2 is true

  • inner if condition number1 == number2 is checked
  • if condition is true , code inside the inner if is executed
  • if condition is false , code inside the inner else is executed

If the outer condition is false , the outer else statement is executed.

Table of Contents

  • Introduction

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Programming

Master the use of if-else statements in Golang to control the flow of your code. A comprehensive guide on if-else syntax, conditions, and nested statements.

Golang If Else Statements (A Complete Guide)

Introduction.

If-else statements are a fundamental part of programming, and Golang is no exception. They allow you to control the flow of your code by executing certain sections of it based on certain conditions. In this article, we will be taking a deep dive into the use of if-else statements in Golang. We will cover everything you need to know about if-else syntax, conditions, and nested statements to help you write efficient and reliable code. Whether you’re a beginner or an experienced developer, this guide will give you a comprehensive understanding of if-else statements in Golang. So, let’s get started

What is an If-Else Statement?

An if-else statement is a control flow statement that allows you to execute certain sections of code based on certain conditions. If the condition is true, the code inside the if block will be executed. If the condition is false, the code inside the else block will be executed.

If-Else Syntax

The syntax of an if-else statement in Golang is as follows:

If-Else Conditions in Golang

The condition in an if-else statement can be any valid boolean expression. It can be a simple boolean variable, a comparison, a logical expression, or a function call that returns a boolean value.

Nested If-Else Statements in Golang

You can also nest if-else statements inside each other. This allows you to create complex conditions and execute different sections of code based on the result of each condition.

Else If Statements in Golang

You can also chain if-else statements together. This allows you to create a series of conditions that will be executed in order. If the first condition is false, the next condition will be checked, and so on. If none of the conditions are true, the code outside the if-else statement will be executed.

This article has provided a comprehensive guide on if-else statements in Golang and with the examples and explanations provided, you should now have a solid understanding of how to use them effectively in your code.

Subscribe to my newsletter

Get the latest posts delivered right to your inbox.

Master Go by Building Redis from Scratch.

codeCrafters logo

Golang Programs

Golang Tutorial

Golang reference, beego framework, golang if...else...else if statements.

In this tutorial you'll learn how to write decision-making conditional statements used to perform different actions in Golang.

Golang Conditional Statements

Like most programming languages, Golang borrows several of its control flow syntax from the C-family of languages. In Golang we have the following conditional statements:

  • The if statement - executes some code if one condition is true
  • The if...else statement - executes some code if a condition is true and another code if that condition is false
  • The if...else if....else statement - executes different codes for more than two conditions
  • The switch...case statement - selects one of many blocks of code to be executed

We will explore each of these statements in the coming sections.

Golang - if Statement

The if statement is used to execute a block of code only if the specified condition evaluates to true.

The example below will output "Japan" if the X is true:

Golang - if...else Statement

The if....else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false.

The example below will output "Japan" if the X is 100:

Golang - if...else if...else Statement

The if...else if...else statement allows to combine multiple if...else statements.

Golang - if statement initialization

The if statement supports a composite syntax where the tested expression is preceded by an initialization statement.

The example below will output "Germany" if the X is 100:

Most Helpful This Week

4 basic if-else statement patterns

if assignment golang

Basic syntax

With init statement, nested if statements, ternary operator alternatives.

An if statement executes one of two branches according to a boolean expression.

  • If the expression evaluates to true, the if branch is executed,
  • otherwise, if present, the else branch is executed.

The expression may be preceded by a simple statement , which executes before the expression is evaluated. The scope of x is limited to the if statement.

Complicated conditionals are often best expressed in Go with a switch statement . See 5 switch statement patterns for details.

if assignment golang

You can’t write a short one-line conditional in Go; there is no ternary conditional operator. Instead of

In some cases, you may want to create a dedicated function.

Go if & else statements

last modified April 11, 2024

In this article we show how to create conditions and branches in Golang.

Go if & else

There can be multiple if/else statements.

Go if/else examples

The following examples demonstrate conditional execution of blocks with if/else.

In the code example we have a simple condition; if the num variable is positive, the message "The number is positive" is printed to the console. Otherwise; nothing is printed.

The message is printed since value 4 is positive.

The else statement specifies the block that is executed if the if condition fails.

Next we add additional branch with if else .

We generate random values between -5 and 4. With the help of the if & else statement we print a message for all three options.

We run the example a few times.

The if statement can start with a short statement to execute before the condition.

Check map key existence

Go has a shorthand notation for checking the existence of a key in a map.

We check if a grade for a particular student exists and if it does, we print its corresponding value.

The Go Programming Language Specification

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

The if-else expression in Golang

The if-statement is present in almost every programming language out there. It is one of the most important control-flow statements in programming. In this post, we will explore the different ways we can use the if statement to make our programs robust and concise.

1. The syntax of if-expression in GoLand

The syntax of the if-statement is pretty simple. The if statement evaluates an expression to a boolean value. If it is true then the code block afterward it executes else it doesn’t.

Here is an example of a simple if expression.

Observe that in the program above, if the condition doesn’t match then nothing happens. No error is thrown.

2. The else clause

The else clause is used to redirect the control flow when the condition doesn’t match in the if expression. Here is an example of an if-else block.

3. The else-if construct in Golang

Else-if is almost the same as if except the flow comes to it when the main if statement doesn’t match and it propagates downwards like a chain. Below is an example of an if-else-if-else chain.

4. If statement with initialization

The if statement in Go can have an initialization at the very beginning. Here is the way to do it.

5. Nested if statements in Golang

If statements can be nested arbitrarily to any depth. Although too deeply nested if construct can lead to bad software design. Here we will explore an example of a nested if statement.

As you can see nesting can be of any depth. The if expression also replaces the needs for the ternary operator .

The if-else is an important control flow statement in the Go programming language.

golang can make choices with data. This data (variables) are used with a condition: if statements start with a condition. A condition may be (x > 3), (y < 4), (weather = rain).

What do you need these conditions for? Only if a condition is true, code is executed.

If statements are present in your everyday life, some examples: - if (elevator door is closed), move up or down. - if (press tv button), next channel

If statements in golang

The program below is an example of an if statement.

golang runs the code block only if the condition (x >2) is true. If you change variable x to any number lower than two, its codeblock is not executed. ### Else You can execute a codeblock if a condition is not true

Video tutorial below

  • Make a program that divides x by 2 if it’s greater than 0
  • Find out if if-statements can be used inside if-statements.

Download Answers

if assignment golang

In Golang we have if-else statements to check a condition and execute the relevant code.

if statement

The if statement is used to check if a condition is met and execute the code inside the if block only if the condition is met.

The general syntax is

Let us write a example code to test if we need to take an umbrella based on if it's raining or not outside.

else statement

If the condition in a if statement is not met then we execute the else block if it is defined.

The syntax is

One thing to remember here is the else statement should always be in the same line as the closing } of the if statement.

In the last module, we checked if it's raining and we gave a message if it is raining. But our code doesn't print anything if it is not raining. Let us fix it by adding an else statement and providing more information.

Let's write an example code to check if the user's name is John or not

You can cascade if statement in an else statement to check for more conditions and run the relevant code.

Now let's write some code to check if a user age is below 20 or between 20 and 60 or above 60.

The if statement also provides an option to initialize a variable and test the condition within the if statement. The general syntax in this case is

An example code is given below.

In a country, a person is allowed to vote if his/her age is above or equal to 18. Check the userAge variable and print "Eligible" if the person is eligible to vote or "Not Eligible" if the person is not eligible.

if assignment golang

Coding for Kids is an online interactive tutorial that teaches your kids how to code while playing!

Receive a 50% discount code by using the promo code:

Start now and play the first chapter for free, without signing up.

if assignment golang

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

golang multiple assignment evaluation

I'm confused on the concept of multiple assignment. Given the following code:

How is the assignment evaluated, given the fact that both variables appear on both the left and right side of the assignment?

Jeroen Jacobs's user avatar

3 Answers 3

The Go Programming Language Specification Assignments The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

The usual example to illustrate multiple assignments is a swap. For example,

Playground: https://play.golang.org/p/HcD9zq_7tqQ

The one statement multiple assignment, which uses implicit temporary variables, is equivalent to (a shorthand for) the two multiple assignment statements, which use explicit temporary variables.

Your fibonacci example translates, with explicit order and temporary variables, to:

Playground: https://play.golang.org/p/XFq-0wyNke9

peterSO's user avatar

The order is defined in Order of Evaluation in the language spec.

At package level, initialization dependencies determine the evaluation order of individual initialization expressions in variable declarations. Otherwise, when evaluating the operands of an expression, assignment, or return statement, all function calls, method calls, and communication operations are evaluated in lexical left-to-right order.

Which comes with a good example of complex evaluation order

y[f()], ok = g(h(), i()+x[j()], <-c), k() the function calls and communication happen in the order f(), h(), i(), j(), <-c, g(), and k(). However, the order of those events compared to the evaluation and indexing of x and the evaluation of y is not specified.

Operands are evaluated left to right. The fact that next is assigned to after the operands are evaluated is irrelevant.

Then there are the Assignments :

The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

So the order here is next then current+next . The result of next is assigned to current , then the result of current+next is assigned to next .

JimB's user avatar

  • 1 But which value of 'current' is used in current+next? Before or after 'next' was assigned to it? –  Jeroen Jacobs Commented Feb 16, 2018 at 23:33
  • @JeroenJacobs: there is only one value of current to use there. Assignment happens after all operands are evaluated. –  JimB Commented Feb 16, 2018 at 23:39

From the spec :

Emile Pels's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged go or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Sylvester primes
  • Can you equip or unequip a weapon before or after a Bonus Action?
  • Best approach to make lasagna fill pan
  • Euler should be credited with PNT?
  • How to connect 20 plus external hard drives to a computer?
  • How to modify orphan row due to break at large footnote that spans two pages?
  • What does 'ex' mean in this context
  • Stained passport am I screwed
  • "It never works" vs "It better work"
  • Current in a circuit is 50% lower than predicted by Kirchhoff's law
  • DateTime.ParseExact returns today if date string and format are set to "General"
  • Representing permutation groups as equivalence relations
  • Why didn't Air Force Ones have camouflage?
  • What's the benefit or drawback of being Small?
  • Pull up resistor question
  • A seven letter *
  • Is there a way to read lawyers arguments in various trials?
  • Are others allowed to use my copyrighted figures in theses, without asking?
  • When has the SR-71 been used for civilian purposes?
  • What does "Two rolls" quote really mean?
  • Are all citizens of Saudi Arabia "considered Muslims by the state"?
  • Does the average income in the US drop by $9,500 if you exclude the ten richest Americans?
  • Did Babylon 4 actually do anything in the first shadow war?
  • In which town of Europe (Germany ?) were this 2 photos taken during WWII?

if assignment golang

IMAGES

  1. Golang if statement

    if assignment golang

  2. If Statements in GoLang

    if assignment golang

  3. Go If Else Statements: Decision Making

    if assignment golang

  4. golang 6

    if assignment golang

  5. Golang Variables Declaration, Assignment and Scope Tutorial

    if assignment golang

  6. Golang Tutorial #4

    if assignment golang

VIDEO

  1. Basic Golang

  2. Virtual Programming Lab and Go Auto-Grading Example

  3. Map-Reduce Golang Assignment Test Cases Passed

  4. If else in golang

  5. 3 Key Updates from Go 1.22

  6. P2P Protocol In Golang For My Distributed CAS

COMMENTS

  1. go

    12. One possible way to do this in just one line by using a map, simple I am checking whether a > b if it is true I am assigning c to a otherwise b. c := map[bool]int{true: a, false: b}[a > b] However, this looks amazing but in some cases it might NOT be the perfect solution because of evaluation order.

  2. Learn if else statement in Go aka Golang with examples

    Learn how to use if, else, if else if and else statements in Go with syntax and examples. See how to check conditions, execute blocks of code and handle errors.

  3. A Tour of Go

    If with a short statement. Like for, the if statement can start with a short statement to execute before the condition. Variables declared by the statement are only in scope until the end of the if. (Try using v in the last return statement.) < 6/14 >. if-with-a-short-statement.go Syntax Imports. 21.

  4. Go if..else, if..else..if, nested if with Best Practices

    Learn how to use conditional statements in Go with examples and best practices. Compare different types of if statements, logical operators, comparison operators and multiple conditions.

  5. How To Write Conditional Statements in Go

    Learn how to use if, if-else, and if-else-if statements in Go to execute code based on conditions. See examples of grade calculation, bank account balance, and ternary operator.

  6. Understanding and Using Golang If Statement

    Remember that in GoLang, as in most programming languages, a single equals sign (=) is used for assignment, while a double equals sign (==) is used for comparison. Also, keep in mind that GoLang is case sensitive. This means that the variables 'a' and 'A' are considered to be different. So, always ensure that you're using the correct case when ...

  7. Go by Example : If/Else

    Learn how to use if and else statements in Go with examples and explanations. See how to use logical operators, multiple conditions, and nested if statements.

  8. Go if else (With Examples)

    Learn how to use the if statement and its variations in Go programming, such as if...else, if...else if and nested if. See syntax, examples and output of each case.

  9. Golang If Else Statements (A Complete Guide)

    Learn how to use if-else statements in Golang to control the flow of your code based on certain conditions. This guide covers syntax, conditions, nested statements, and else if statements with examples and explanations.

  10. Golang If...Else...Else If Statements

    Learn how to write decision-making conditional statements in Golang, including if, if...else, and if...else if...else. See syntax, examples, and output for each ...

  11. 4 basic if-else statement patterns ¡ YourBasic Go

    Basic syntax; With init statement; Nested if statements; Ternary ? operator alternatives; Basic syntax if x > max {x = max } if x = y {min = x } else {min = y }. An if statement executes one of two branches according to a boolean expression.. If the expression evaluates to true, the if branch is executed,; otherwise, if present, the else branch is executed.; With init statement

  12. Go if & else statements

    With the help of the if & else statement we print a message for all three options. $ go run main.go. The number is positive. $ go run main.go. The number is zero. $ go run main.go. The number is negative. We run the example a few times. The if statement can start with a short statement to execute before the condition.

  13. The if-else expression in Golang

    Learn how to use the if-statement, the else clause, the else-if construct, and the initialization and nesting of if statements in Go. See examples of simple and complex if expressions and their output.

  14. If statements

    golang can make choices with data. This data (variables) are used with a condition: if statements start with a condition. A condition may be (x > 3), (y < 4), (weather = rain). The program below is an example of an if statement. golang runs the code block only if the condition (x >2) is true. If you change variable x to any number lower than ...

  15. If-Else

    Learn how to use if-else statements in Golang to check conditions and execute code blocks. See examples, syntax, and exercises on comparing values, checking age, and printing messages.

  16. Anatomy of Conditional Statements and Loops in Go

    After the execution of post statement, condition statement will be evaluated again. If condition returns true, code inside for loop will be executed again else for loop terminates. Let's get ...

  17. A Tour of Go

    If and else

  18. A Tour of Go

    Learn how to use switch statements in Go, a shorter way to write a sequence of if - else statements. See examples of switch cases with different values and expressions, and how to break out of them.

  19. syntax

    A short variable declaration uses the syntax: ShortVarDecl = IdentifierList ":=" ExpressionList . It is a shorthand for a regular variable declaration with initializer expressions but no types: "var" IdentifierList = ExpressionList . Assignments. Assignment = ExpressionList assign_op ExpressionList . assign_op = [ add_op | mul_op ] "=" .

  20. go

    The one statement multiple assignment, which uses implicit temporary variables, is equivalent to (a shorthand for) the two multiple assignment statements, which use explicit temporary variables. Your fibonacci example translates, with explicit order and temporary variables, to: package main. import "fmt". func fibonacciMultiple() func() int {.

  21. A Tour of Go

    Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type. Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available. < 10/17 >. short-variable-declarations.go Syntax Imports.