DEV Community

Eternal Dev for Eternal Dev

Posted on • Originally published at eternaldev.com on

Go - If Else Statement

#go

Conditional statement form the basics of any program and you will learn how to write if else statement in Go with practical examples

Go - If Statement

Starting out, we have the basic if statement to run some logic when a particular statement is true

package main

import "fmt"

func main() {
    percentage:= 75

    if percentage > 50 {
        fmt.Println("You hold a majority!")
    }
}
Enter fullscreen mode Exit fullscreen mode

Go execute the statements within the braces when the condition is true

Go - If... Else... Statement

Else statement helps in executing the statements when the if condition is false

package main

import "fmt"

func main() {
    percentage:= 33

    if percentage > 50 {
        fmt.Println("You hold a majority!")
    } else {
        fmt.Println("You don't hold a majority")
    }
}
Enter fullscreen mode Exit fullscreen mode

Go - If... Else if... Else... Statement

When you have multiple conditions to check, you can use this format to check all the needed condition and then execute statement which match those conditions

package main

import "fmt"

func main() {
    percentage:= 33

    if percentage > 50 {
        fmt.Println("You hold a majority!")
    } else if percentage > 30 && percentage <= 50 {
        fmt.Println("You have decent amount")
    } else {
        fmt.Println("Please check your life choices")
    }
}
Enter fullscreen mode Exit fullscreen mode

Go - If... with init Statement

Variables can be initialized at the state of the if statement and these variables are scoped within the conditional statement block. If you try to access the variable outside the if statement, you will recieve "undefined: {variable name}" error

package main

import "fmt"

func main() {

    if percentage:= 76; percentage > 50 {
        fmt.Println("You hold a majority!")
    } else if percentage > 30 && percentage <= 50 {
        fmt.Println("You have decent amount")
    } else {
        fmt.Println("Please check your life choices")
    }
}
Enter fullscreen mode Exit fullscreen mode

Practical Assignment - Try these out

  1. Build an application which prints out the person's eligibility to vote after getting the age of the person
  2. Build an application which will print out the messages based on the time of the day

Join our discord channel and ask question if you have on doing these assignments

Check out live online editor here

Conclusion

Stay tuned by subscribing to our mailing list and joining our Discord community

Discord

Top comments (2)

Collapse
 
kishanbsh profile image
Kishan B

Syntax highlighting on code snippets would make it much better :-)

You can add it by typing "go" in the beginning of the code fence.

Collapse
 
eternal_dev profile image
Eternal Dev

Thanks for the tip. Will try to update the posts