Go - If Else Statement

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!")
    }
}
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")
    }
}
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")
    }
}
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")
    }
}
Practical Assignment - Try these out
  • Build an application which prints out the person's eligibility to vote after getting the age of the person
  • 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

    29

    This website collects cookies to deliver better user experience

    Go - If Else Statement