IF and Else statement in Golang

IF and Else statement in Golang

·

3 min read

What are IF and else statement in GO**

They are called conditional statement..imagine you want a block of code to run on a certain condition like if ada is 2 years something should happen otherwise something else should happen .Without much talk let us Dive straight into the code and see what amazing stuff lies ahead of us

I will be using vscode throughout this tutorial process process..you can use any code editor ..create a file and name it

main.go

Screenshot from 2020-08-22 03-12-19.png

this is how it will look like we should now import the our main package which will define the functions in which our code will stay where all the code will stay and be executed like so

Package main

Then after that we need to define our func

func main(){

}

Screenshot from 2020-08-22 03-31-36.png

like so

so to create a condition we need to check something so we will need to create variables first... if you dont know how to create variables i have an article on that here like so we will create an integer to check if it is equal to something then we would print a statement

a:= 5

then for the if and else statement we can check if a is equal to 5 the we would print A is equal to 5 if not wee will print A is not equal to 5

so after assigning a we would use the double equal == sign to check if it is equal or not

if a == 5{
fmt.Println("a is equal to 5")
}else{
"a is not equal to 5"
}

PS: you will need to import the fmt package like this if you don't have the auto import feature

import "fmt"

when you do

go run main.go

Screenshot from 2020-08-22 03-47-50.png this should be the result

you can do other stuff with it like

if 4/2 != 2 {
fmt.Println("the answer is wrong ")
}

the != sign stands for

not equal to

now for the next thing for you to know is that you can create a special condition of your if condition with the keyword

else if

let us test with the variable we create a

we are going to be checking if a is greater than 1 then we are going to be checking if a is equal to 5

    if a > 1 {
        fmt.Println("great")

    } else if a == 5 {
        fmt.Println("a is greater than 5")
    } else {
        fmt.Println("nahhh")
    }

now if you run main

go run main.go

you will get something like this

Screenshot from 2020-08-22 03-56-57.png

I hope you understand how to use conditional statement if and else now in GO