How to write an if conditional statement in Golang or Go?

Published July 13, 2022

To write an if conditional statement in Golang/Go, you have to write the keyword if followed by the condition you want to check and then the opening and closing curly brackets symbol ({}). Inside the curly brackets, you can write the code to run for that specific condition.

For example, let's write an if conditional statement where it checks if the number 3 is less than the number 5.

It can be done like this,

package main
import "fmt"

func main() {
    // this is the if conditional statement
    if 3 < 5 {
        fmt.Printf("I'm inside the if block!")
    }
}

As you can see from the above code, we have written the if keyword followed by the condition which is 3 < 5 and then the opening and closing curly brackets symbol ({}).

Inside the if block we are just printing the text I'm inside the if block!.

We have successfully made an if conditional statement in Golang. Yay 🥳!

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this helpful 😃.


Share on: Facebook Twitter