Skip to main content

Command Palette

Search for a command to run...

Conditional Statements in Go

Updated
2 min read
Conditional Statements in Go
P

👋 Hey there!

I'm a community-driven software engineer, and I absolutely love diving into the world of cloud-native development and exploring the endless possibilities of open-source technologies. 💻

My skill set revolves around Kubernetes, GoLang, Python, Docker, and other fascinating container technologies. 🚀 And hey, just to add to the mix, I'm also CKA certified! 🎓

But you know what? My journey doesn't stop at coding. I have a genuine passion for technical evangelism. 🎤 I've had the privilege to speak at world-renowned events, sharing my knowledge and insights with others. It's such an exhilarating experience! And when I'm not on stage, you can find me pouring my thoughts into engaging technical blogs. 📝

If you've made it this far and you're intrigued by what you've read, let's not leave it at that! Reach out, and let's connect. Who knows what exciting opportunities may be awaiting us? 😊

Conditional Statements are part of every programming language. They help us to decide which instruction is supposed to run when a certain condition is met. e.g. If I’m hungry then I’ll eat else I’ll wait. e.g. If the score is greater than 35%, you passed, else you failed.

If statement in Go

if condition/expression {
    //instruction to be performed
}

The condition needs to be true to perform the given set of instructions.

package main

import "fmt"

func main(){
    i := 10
    if i % 2 == 0 {
        fmt.Printf("%d is a even number", i)
    }
}

Run this code in Go Playground

If-Else statement in Go

if condition/expression {
    //instruction to be performed
} else {
    //instruction to be performed
}

If the condition needs to be false perform instruction from the else block.

package main

import "fmt"

func main(){
    i := 11
    if i % 2 == 0 {
        fmt.Printf("%d is a even number", i)
    } else {
        fmt.Printf("%d is a odd number", i)
    }
}

Run this code in Go Playground

if-else-if ladder

We can use multiple conditional statements at once.

package main

import "fmt"

func main(){
    i := -11
    if i == 0 {
        fmt.Println("It's zero")
    } else if i < 0 {
        fmt.Println("Negative number")
    } else {
        fmt.Println("Positive number")
    }
}

Run this code in Go Playground

Short statement

package main

import "fmt"

func main() {
    if j := 10; j%2 == 0 {
        fmt.Println("Even number")
    }
}

Run this code in Go Playground

Thank you for reading this blog, and please give your feedback in the comment section below.

More from this blog

pratikjagrut.space

32 posts